What is Singleton Design Pattern?
- Ensures a class has only one instance and provides a global point of access to it.
- A singleton is a class that only allows a single instance of itself to be created, and usually gives simple access to that instance.
- Most commonly, singletons don't allow any parameters to be specified when creating the instance, since a second request of an instance with a different parameter could be problematic! (If the same instance should be accessed for all requests with the same parameter then the factory pattern is more appropriate.)
- A single constructor, that is private and parameterless.
- The class is sealed.
- A static variable that holds a reference to the single created instance, if any.
- A public static means of getting the reference to the single created instance, creating one if necessary.
Advantages
The advantages of a Singleton Pattern are:
- It can be also inherit from other classes.
- It can be lazy loaded.
- It has Static Initialization.
- It provides a single point of access to a particular instance, so it is easy to maintain.
Disadvantages
The disadvantages of a Singleton Pattern are:
- Unit testing is more difficult (because it introduces a global state into an application).
Thread Safety Singleton
- This implementation is thread-safe.
- In the following code, the thread is locked on a shared object and checks whether an instance has been created or not.
- This takes care of the memory barrier issue and ensures that only one thread will create an instance.
- For example: Since only one thread can be in that part of the code at a time, by the time the second thread enters it, the first thread will have created the instance, so the expression will evaluate to false.
- The biggest problem with this is performance; performance suffers since a lock is required every time an instance is requested.
public sealed class Singleton
{
Singleton()
{
}
private static readonly object padlock = new object();
private static Singleton instance = null;
public static Singleton Instance
{
get
{
lock (padlock)
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
}
Singleton class vs. Static methods
The following conpares Singleton class vs. Static methods:
- A Static Class cannot be extended whereas a singleton class can be extended.
- A Static Class can still have instances (unwanted instances) whereas a singleton class prevents it.
- A Static Class cannot be initialized with a STATE (parameter), whereas a singleton class can be.
- A Static class is loaded automatically by the CLR when the program or namespace containing the class is loaded.
No comments:
Post a Comment