Growing with the Web

Singleton design pattern

Published , updated
Tags:

The singleton design pattern enables easy access to a single instance of a class.

Benefits

  • Makes it very easy to get a single instance of an object globally

Drawbacks

  • They are effectively just globals, this is not object-oriented design
  • Can cause concurrency issues if not the singleton is not thread-safe
  • Can make code hard to follow
  • Makes unit testing more difficult

From the looks of the benefits and drawbacks you would wonder why you would use a singleton at all, a lot of people even consider it an anti-pattern. My answer to that question is that you should only use this pattern very sparingly and preferably not at all in large projects. You can however save yourself quite a bit of time using them in small projects.

UML diagram

Note the private constructor.

Singleton UML diagram

Code examples

Traditional singleton

public class Singleton
{
    private static Singleton _instance = new Singleton();

    private Singleton() { }

    public static Singleton Instance
    {
        get { return _instance; }
    }
}
public class Singleton
{
    private static Singleton instance = new Singleton();

    private Singleton() { }

    public static Singleton getInstance()
    {
        return instance;
    }
}

Singleton with lazy loading

public class LazyLoadingSingleton
{
    private static LazyLoadingSingleton _instance;

    private LazyLoadingSingleton() { }

    public static LazyLoadingSingleton Instance
    {
        get
        {
            if (_instance == null)
                _instance = new LazyLoadingSingleton();

            return _instance;
        }
    }
}
public class LazyLoadingSingleton
{
    private static LazyLoadingSingleton instance;

    private LazyLoadingSingleton() { }

    public static LazyLoadingSingleton getInstance()
    {
        if (instance == null)
            instance = new LazyLoadingSingleton();

        return instance;
    }
}
var SingletonExample = function () {
  if (SingletonExample.prototype.instance) {
    return SingletonExample.prototype.instance;
  }
  SingletonExample.prototype.instance = this;
};

Usage examples

Some common uses of the Singleton design pattern are:

  • Caches
  • Handling user preferences
  • Factory or builder classes

Comments

comments powered by Disqus
Like this article?
Subscribe for more!