Tuesday, December 30, 2008

Singleton Sample

Singleton - Construction should be private. Should allow to create instance using members method(CreateInstance):

namespace ConsoleApplication1
{

class Singleton
{
public static Singleton obj = null;
private Singleton( )
{
}

public static Singleton CreateInstance()
{
if ( obj == null )
obj = new Singleton( );

return obj;
}
}

class Class1
{
static void Main( string[ ] args )
{
Singleton obj1 = Singleton.CreateInstance( );

Singleton obj2 = Singleton.CreateInstance( );
if ( obj1 == obj2 )
Console.Write( "Objects are same" );
}
}
}

No comments: