A Curious Mind
#tastic

The Singleton Pattern

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


Feedback

# re: The Singleton Pattern

Please not that your implementation of the singleton pattern is not thread safe. Instead of me explaining the hows and the why's I would recommend that you read Jon Skeet's article on the implementation of the design pattern:

http://www.yoda.arachsys.com/csharp/singleton.html 8/21/2006 7:49 PM | Gabriel Lozano-Moran

# re: The Singleton Pattern

Ingore my previoust, I did not notice the last line. 8/21/2006 7:50 PM | Gabriel Lozano-Moran

Post a comment





 

Please add 7 and 5 and type the answer here: