Exploring the Singleton Pattern
In some situations, we want to have an instance of a class with public instance methods (not static methods), but never more than one instance of our class.
Exploring the Singleton pattern.
In some situations, we want to have
an instance of a class with public instance methods (not static methods), but
never more than one instance of our class. An example might be where hardware
is being accessed, such as an audio card, and we want to ensure that for thread
safety that we never have more than one instance of the native code handle to
the resource alive.
This is where the Singleton pattern comes into
play. Here is a simplified console app example of a Singleton class "Utils"
with an ID field that
is constructed solely to show that we can never
have more than one instance of our class. Start a new Console application and
paste all the code
below into it:
void Main(string args)
Utils u = Utils.Instance ;
Instance ID: " +u.Id.ToString());
// Sleep the thread for a second
just to prove the single instance ID doesn't change
Utils u2 = Utils.Instance ;
Method Call: "+ u2.SayHello("test"));
public sealed class Utils
this.Id= new System.Random((int)DateTime.Now.Ticks ).Next();
public static readonly Utils Instance = new Utils();
public string SayHello(string input)
Submission Date: 9/23/2005
Submitted By: Peter Bromberg
My Home Page: http://www.eggheadcafe.com
By Peter Bromberg Popularity (638 Views)