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:
using System;
namespace
SingletonDemo
{
class Tester
{
[STAThread]
static
void Main(string[] args)
{
Utils u = Utils.Instance ;
Console.WriteLine("First
Instance ID: " +u.Id.ToString());
// Sleep the thread for a second
just to prove the single instance ID doesn't change
System.Threading.Thread.Sleep(1000);
Utils u2 = Utils.Instance ;
Console.WriteLine("Second Instance
ID: "+u2.Id.ToString());
Console.WriteLine("Non-static public
Method Call: "+ u2.SayHello("test"));
Console.ReadLine();
}
}
public sealed class Utils
{
private
Utils()
{
this.Id= new System.Random((int)DateTime.Now.Ticks ).Next();
}
public static readonly Utils Instance = new Utils();
public
int Id;
public string SayHello(string input)
{
return "hello,
" +input;
}
}
}
Submission Date: 9/23/2005
3:13:39 PM
Submitted By: Peter Bromberg
My Home Page: http://www.eggheadcafe.com
By Peter Bromberg Popularity (637 Views)