Singleton pattern is very popular pattern used by programmer. The idea behind the singleton pattern is to have only one instance of a class at any time. This kind of pattern is very useful for for heavy resources like Linq Data Context etc. It is also useful in multithreaded application where different thread of application try to crate instance of one class but it should be thread safe. It can be also useful for global resources and state objects. In singleton class there are two things required. One static variable which hold the instance of class and other is a static method which will return the instance of singleton class. Here is the example of singleton class
public class MySingleTon { private static MySingleTon mySingleTonInstance = new MySingleTon(); private MySingleTon() { //private constructor } public static MySingleTon GetInstace() { return mySingleTonInstance; } }
MySingleTon objSingleTon = MySingleTon.GetInstace();The above example is not thread safe so it may be possible that different thread can create different instance of classes. To make above singleton class thread safe we need to change code like following.
public class MySingleTon { private static MySingleTon mySingleTonInstance = new MySingleTon(); private MySingleTon() { //private constructor } public static MySingleTon GetInstace() { lock (typeof(MySingleTon)) { if (mySingleTonInstance == null) { mySingleTonInstance = new MySingleTon(); } return mySingleTonInstance; } } }
No comments:
Post a Comment