Monday, December 24, 2007

Singleton Pattern (1) Structure


using System;

namespace DoFactory.GangOfFour.Singleton.Structural

{

class MainApp

{

static void Main()

{

// Constructor is protected -- cannot use new

Singleton s1 = Singleton.Instance(); //this will call: instance = new Singleton();

Singleton s2 = Singleton.Instance(); //this will use the reference created above

if (s1 == s2)

{

Console.WriteLine("Objects are the same instance");

}

Console.Read();

}

}

//-----------------------------------------------------------------------

class Singleton

{

//static field

private static Singleton instance; //use static because we don't want to create instance of the class

// protected constructor

protected Singleton()

{

}

//static method

public static Singleton Instance() //use static because we don't want to create instance of the class

{

// Uses lazy initialization

if (instance == null)

{

instance = new Singleton();

}

return instance;

}

}

}

Singleton

blog comments powered by Disqus