Home  /  Questions  /  Question

80   96.4
May 16, 2010

Singleton Design Pattern


I have a question about the Singleton design pattern.

Is Singleton pattern about maintaining one instance of a class or is it about maintaining one state of a class. What I can think of is this: if it's about creating one instance of a class then static classes are not a way of implementing Singleton design pattern. But if it's about maintaining one state of a class then there is nothing like monostate pattern.

Please advice.

May 16, 2010
Singleton Pattern is a creational pattern and is all about making sure we have only one instance (maximum) of a class at any given point in time.

It just needs a private constructor so that none of the external instances can directly create an instance of the singleton class under consideration. This Singleton class needs to expose one public method eg: GetInstance, which intenally calls the private constuctor only if there is no preexisting instance of the class. Lock statements can be used in the implementation to avoid any hassles of multi-threaded access to the Singleton.

 1 comment
Hey Sreenivas, Thanks for your response. But my main interest is in knowing that if we can implement Singleton pattern using static class or not? If not then no issue. I know that will be called Monostate pattern. But, if yes then how is it different form Monostate pattern and what about having a single instance and synchronized private constructor? --- Ram Pandey  May 17, 2010

1,128   99.9
May 17, 2010
Some differences between Singletons and Static classes are...

* Singletons can implement interfaces

* You cannot pass a static class as a parameter to a method, this can be done with a Singleton

* A Singleton is a normal class that is instantiated just once, a static class is never instantiated

As a side note, I usually tend not to use either of these. Instead I use my DI container (Ninject, StructureMap, ...) to supply me with a singleton of the required type when needed.

70   96.1
May 21, 2010

Go through this link, you will have better understanding of singleton pattern