Wednesday, 2 November 2011

What Is Singleton Design Pattern?Implementation in C#

The singleton design pattern is a concept that allows a class to enforce that it is only allocated once. It is the same in every language.

Here is the implementation of Singleton Class



class Program
{ 
static void Main(string[] args) 
{ 
Singleton obj = Singleton.Instance; 
obj.method(); 
Console.ReadKey(); 
} 
} 

public class Singleton 
{ 
private static Singleton instance; 

private Singleton() { } 

public static Singleton Instance 
{ 
get 
{ 
if (instance == null) 
{ 
instance = new Singleton(); 
} 

return instance;

} 
} 

public void method() 
{ 
Console.WriteLine("In Method 1"); 
} 
} 




Now in above code we cannot made object of class directly due to private constructor but we made object by accessing static property of instance.





This instance is also declared as static. So as much instance we created they all referenced same memory or we can say these all objects accessing same memory, which is reserved for static instance declared in class


Thanks Happy Coding :)

References: Msdn

3 comments: