- There must be one and only one instance of this class. For example, there is one and only one instance of an application. Even in this case, Singleton pattern is not recommended. If there are two modes of this applications, polymorphism will be hard to use when using an Application Singleton. In this case, it is a mere coincidence that we need one instance of this object, but not a design requirement.
- This instance must never die. This means that this particular class needs to stay alive until the end of application life cycle.
- Creation of this object has to be done in a lazy way. This means that the application doesn’t care about when this object is created.
- This object must be responsible for creating itself. There are risks associated with coupling creation and business implementation of an object. This has to be judged carefully.
- This class will dispose of any unmanaged resources in a manual way. Since an instance of this class will be created lazily, but it will stay alive until the end of application life cycle, it has to dispose of unmanaged resources such as WCF channels, file and memory streams, etc. right after it is done using them.
- There will never be a need to create Mock and Dummy objects of this type. Singletons make testing difficult, and sometimes impossible. For example, Logger.Instance singleton cannot be substituted with a mock object because it creates itself.
- It is understood that this class will implement some thread safety since it could be accessed by a number of threads in the application.
Friday, August 13, 2010
Design Problems with Singletons
Following is a design guideline for implementing the Singleton design pattern. This guideline is composed using some key computer science principles such as the Single Responsibility Principle, Liskov Substitution Principle, Dependency Inversion Principle, and KISS.
Subscribe to:
Posts (Atom)