Monday, August 21, 2006 2:56 PM
[This post is another organizing bit for my presentation]
The Singleton Pattern is all about ensuring a single instance of a given class and providing global access to it. The typical C# Singleton class is going to look something like*:
public sealed class Printer
{
private static Printer _instance;
public static Printer Instance
{
if(_instance == null)
_instance = new Printer();
return _instance
}
}
So hear you can see that we have accomplished our two goals. A single instance of the Printer class, by putting the creation behind an if statement that will make sure there is only one instance. Our second goal of global access is accomplished by making the Instance method static. You can now get access to your instance like so:
public void MyMethod()
{
Printer myPrinter = Printer.Instance;
}
Next up: The skeletons in a Singleton's closet.
* This is not a great example of production Singletons. For that read the following: http://www.yoda.arachsys.com/csharp/singleton.html