- Class will have only one instance
- And there will be a global point to access it
Reference:
http://www.dofactory.com/Patterns/PatternSingleton.aspx
How to implement singleton?
- Create private constructor for CLASS
- Declare a static member of the CLASS
- Declare a static property , in which new object of CLASS creates if it does not exist.
Sample:
class Singleton
{
private static Singleton instance;
private Singleton() {}
public static Singleton Instance
{
get
{
if(instance ==null)
{
instance= new Singleton();
}
return instance;
}
}
}
class TestSingleton
{
private TestSingleton()
{
}
public static void DoTest()
{
////Singeleton
Singleton obj1 = Singleton.Instance;
Singleton obj2 = Singleton.Instance;
// Test for same instance
if (obj1 == obj2)
System.Console.WriteLine("both instances are same!");
}
}
No comments:
Post a Comment