Thursday, November 25, 2010

Singleton Pattern

What Is It?

- In this pattern we only create one and only one instance of the class.
- And this class is responsible for the initialization of the instance.
- This is a creational pattern since it is mainly focused on the initialization of an object.
- This instance of the class which is created will be responsible for all the operations related to at class throughout the system.
- Initialization will be done at the first use of the instance.

How to Do?

- What we have to do is so simple.
- Create a public class that cannot be inherited (sealed).
- Create private static attribute (Named instance) of same type (type of the class just created.)
- Create a private Constructor for the class therefore it cannot be initiated outside the class.
- Create a public property of same type which will return the private static attribute of the same type.
- Inside the property we have to check whether it is already created as shown in the below code.



- As shows in the following code snippet you can check whether it returns the same instance of the object.



- Class diagram.
















- Output of the program



When to use?

- When global point of access required
- When the ownership and the initialization responsibilities cannot be ssigned.
- When lazy initialization is desired.

When should not user?

- When we need to pass an object instance as a reference.
- When the exposure and the protection of the object is critical.

Drawbacks

- Make unit test more difficult since it provides the global state to the application.
- Reduces the potential parallelism within the program because access to the singleton in multi-threaded context must be serialized.


Singleton Vs Static classes

Singleton
Static

 1. Can dispose objects

 Cannot dispose the object

 2. Instantiates at the first use the object

 Instantiates when the  program starts


References

- Singleton Design pattern (Source Making)
- C# Singleton pattern Vs Static Classes (.net Zone)
- Singleton (Do Factory)
- Singleton Pattern (Wikipedia)