Singleton pattern is one of the easiest patterns that we can
implement. However, if not properly implemented it would result many issues in
the system which using this pattern. Industrially, the Singleton pattern heavily
used whenever the application needs to access external resources such as file
reads and database access.
The main objective of the singleton pattern is to maintain
only one instance of a class. Normally the constructor of a singleton class
does not have any parameters. Because having a parameter means there would be
different behavior based on the constructor.
Following is an example to a s Singleton class.
public class Singleton
{
private static Singleton _instance;
private Singleton()
{
}
public static Singleton Instance
{
get
{
if (_instance == null)
{
_instance = new Singleton();
}
return _instance;
}
}
public void DoWork()
{
}
}
Note that the constructor to this class is private. This means
that external classes cannot create instances of this class. The instance needs
to get created the class within itself.
Using the Singleton pattern is very easy. All we need to do
is just refer the instance as follows.
Singleton.Instance.DoWork
();
Or
SomeMethod(Singleton.Instance);
Being the implantation is very simple; the Singleton pattern
is NOT thread safe. This is the main disadvantage of this pattern over its simplicity.
Most of the current applications are running on threaded
environments and hence following is the way we can make the Singleton pattern thread
safe.
One way that we can make the singleton thread safe is ,
using locks. But this is effecting to the performance of the application.
Following is a way we can make the singleton pattern thread
safe. This is using the way that type initializers work in .Net. if the type is
not marked as “Beforefieldinit ” , the type initialization happens on-demand in
the compiler. Ie : lazy implementation.
Following is the code
public class LazySingleton
{
private LazySingleton()
{
}
public static LazySingleton Instance
{
get { return Nested.instance; }
}
private class Nested
{
static Nested()
{
}
internal static readonly LazySingleton instance = new LazySingleton();
}
}
One consequence of the Singleton pattern is , it is not easy
to test it. We can avoid this using IOC. I will explain that in a different
blog post.
No comments:
Post a Comment