< Day Day Up > |
17.3 Singleton Versus Class Methods and Class PropertiesYou might wonder why we wouldn't implement the Logger class's functionality entirely in class methods and class properties. That is, why not design Logger to be used directly through class methods instead of through a solitary instance? The Singleton pattern is used in favor of a class that simply groups class methods and class properties together for two key reasons. First, flexibility. Once established, the Singleton pattern is very easy to change from a "sole-instance" implementation to a multiple-instance implementation. For example, if down the road we decide to use separate Logger instances to log different aspects of our application, we can easily update the Logger class to allow the creation of multiple instances. In contrast, moving functionality from class methods and class properties to individual instances would be much more work. Second, inheritance. As we've just seen with the Logger class, the Singleton pattern works freely with inheritance. For example, our Logger class (a Singleton) extends Observable without issue. In contrast, a class used solely through its class members cannot meaningfully extend a class used through its instances. If Logger were used entirely through class methods, it could not inherit the functionality of the Observable class because Observable must be instantiated to work. The inverse is also true: a class comprised solely of class members is difficult to extend (sometimes prohibitively so) because of the scope issues described in Chapter 6. The Singleton pattern gives us the benefits of centralized access to some aspect of a program without the limitations of class methods and class properties. |
< Day Day Up > |