Singleton Pattern
Singleton Pattern
The first pattern in the creational pattern series is the singleton pattern.
You can read my previous posts about design patterns here:
Structural patterns
Decorator pattern
Proxy pattern
Facade pattern
Adapter pattern
Composite pattern
Bridge pattern
Flyweight pattern
Introduction
The singleton pattern is a very useful pattern.
I encountered it while I was a second year student in an object oriented
course I took. During that course we had a lecture about design patterns and
the singleton pattern was one of the patterns that were discussed.
Think about it, one lecture about design patterns in a course about object oriented...
What is the Singleton Pattern?
The singleton pattern ensures that a class has one instance only.
Also, it provides the access point to the get the that single instance.
For a UML diagram of the pattern go to dofactory site.
Example in C#
How does it works? lets look at an example:
class Singleton
{
#region Members
// the only instance of the singleton object
private static Singleton _me;
// lock synchronization object
private static object syncLock = new object();
#endregion
#region Properties
/// <summary>
/// Get the instance of the singleton
/// </summary>
public static Singleton Instance
{
get
{
// handle the creation only once and if
// needed also the implementation is
// thread safe
if (_me == null)
{
lock (syncLock)
{
if (_me == null)
{
Singleton newInstance = new Singleton();
System.Threading.Thread.MemoryBarrier();
_me = newInstance;
}
}
}
return _me;
}
}
#endregion
#region Ctor
private Singleton()
{
}
#endregion
The implementation is thread safe. I lock the syncLock object and then create
the instance of the singleton only once. After that, the instance will be returned
every time it is being asked by the Instance property.
I added the MemoryBarrier call on the thread to correct the implementation
I made earlier thanks to the comment of Arnon. Look at the post of Eran Kampf for details.
Summary
To sum up the post, you should use the pattern whenever you need to be sure that only
single instance of a class is created. As I wrote the singleton is very useful.
Be aware that using a static object (the singleton object) has a performance issue
(because it is static) and therefore use the pattern carefully.
The next stop in the creational patterns - the abstract factory.