Singleton’s implemented the right way

The Singleton pattern implementation out of the gang of four book [Gamma, Helm, Johnson, and Vlissides. Design Patterns: Elements of Reusable Object-Oriented Software. Addison-Wesley, 1995.] is not thread save (at least in C# it isn’t). Besides that it uses a GetInstance() method and makes not use of C# properties. I think a simple Instance property is nicer and follows the general C# style.

Check out my version of a Singleton implemenation:

public class Singleton 

{ 

    private readonly static Singleton singleton = new Singleton(); 

    public static Singleton Instance() 

    { 

        return singleton; 

    } 

    private Singleton() 

    { 

    } 

}

Upsides of this approach are that it is thread save and look quite simple. Downside is you don’t have exact control over when the Instance is created. In the few cases where this is important (Let’s say the creation of the instance is very time consuming and you want to guarantee that it is only created when needed you might want to check out the double-check locking approach more detailed explained here: http://msdn2.microsoft.com/en-us/library/ms998558.aspx.

The double-check locking approach is also a solution if you need to do some extra stuff when you create the one instance.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>