The singleton patterns ensures a class has only one instance, and provide a global point of access it.
More information
To assure there is one and only one instance, first we can disable the object creation by making constructor private. Then secondly we can mark instance variable/method to static to ensure only one instance and to provide access point.
The Instance() method is the method that return the singleton instance. We can mark this method as lock (syncronized) to make thread safe. But lock (syncronized) is not good for performance. So what are the other available options,
- No worry about the Instance method if the performance is not important :P
This is obvious, if the performance is not a critical factor then you can use syncronization.
- Do the instance creation as eagerly created rather than a lazy created one
Static constructors in C# are specified to execute only when an instance of the class is created or a static member is referenced, and to execute only once per AppDomain.
- Use double check locking to reduce the use of syncronized Instance method
C# you can easily do this but in Java you need to do this with Volatile keyword. Also you need Java 1.5 or higher version. Please see the reference for more details.
Implementation
internal class Singleton
{
private static Singleton _instance = new Singleton();
private string _property = "Singleton Property";
private Singleton()
{
}
public string Property
{
get { return _property; }
set { _property = value; }
}
public static Singleton Instance
{
get { return _instance; }
set { _instance = value; }
}
}
This implementation is a lazy implementation of the singleton pattern. This is not a thread safe version.
internal class SingletonLazy
{
private static SingletonLazy _instance;
private string _property = "Singleton Property";
private SingletonLazy()
{
}
public string Property
{
get { return _property; }
set { _property = value; }
}
public static SingletonLazy Instance()
{
if (_instance == null)
{
_instance = new SingletonLazy();
}
return _instance;
}
}
This is the Main program to work with above classes.
internal class Program
{
private static void Main(string[] args)
{
// The non lazy initialization
Singleton nonLazySingleton1 = Singleton.Instance;
Singleton nonLazySingleton2 = Singleton.Instance;
nonLazySingleton1.Property = "The new Property";
if (nonLazySingleton1.Property.Equals(nonLazySingleton2.Property))
{
Console.WriteLine("The non lazy singleton is successful");
}
// The lazy initialization
SingletonLazy singletonLazy1 = SingletonLazy.Instance();
SingletonLazy singletonLazy2 = SingletonLazy.Instance();
singletonLazy2.Property = "The new Property";
if (singletonLazy1.Property.Equals(singletonLazy2.Property))
{
Console.WriteLine("The lazy singleton is successful");
}
}
}
Reference:
http://www.yoda.arachsys.com/csharp/singleton.html
No comments:
Post a Comment