Singleton Pattern
The singleton pattern is one of the simplest design patterns. It involves only one class which is responsible to instantiate itself, to make sure it creates not more than one instance, in the same time it provides a global point of access to that instance. In this case the same instance can be used from everywhere, being impossible to invoke directly the constructor each time.
Context:
It's important to have only one instance for a class. For example, in a system there should be only one window manager (or only a file system or only a print spooler). Usually singletons are used for centralized management of internal or external resources and should provide a global point of access to objects.
Problem:
Singletons are very similar to Global Variables. Singleton Pattern has to do with how to limit instances. singletons have problems similar to globals; e.g., creating dependencies in vastly separated parts of the system, so side effects can appear far afield from their causes.
example problem statement by Daneil Earwicker: Imagine if a class A was using class D, which is a database access library. So within the implementation of A, it keeps declaring instances of D and using them to query a database. To make a Unit test for A, you have to declare a stub version of D that returns typical dummy values.
The singletons you describe above are no different from class D, really. I don't think you can get away from that. The dependencies of a class are not always made obvious in its interface. Personally, I think other the problems you mention are more annoying, and I would be itching to sort them out - otherwise there's a danger that your tests will be as confused as the classes.
Solution:
A better solution is to make the class itself responsible for keeping track of its instance. The class can ensure that no other instances can be created to create new objects and it can provide a way to access the instance.
Example - Configuration Classes
The Singleton pattern is used to design the classes which provides the configuration settings for an application. By implementing configuration classes as Singleton not only that we provide a global access point, but we also keep the instance we use as a cache object. When the class is instantiated( or when a value is read ) the singleton will keep the values in its internal structure. If the values are read from the database or from files this avoids the reloading the values each time the configuration parameters are used.
No comments:
Post a Comment