The Singleton belong to the Creation Patterns. It ensures that only one instance of that specific class can be created and it provides an global access to that instance.

For example an Abstract Factory can be created with it. This way it ensures that you can access the factory from everywhere.

GuiFactory.getInstance().createButton();

An simple Java implementation for a Singleton would look something like this:

public final class Singleton {

    private static final Singleton INSTANCE = new Singleton();

    private Singleton() {}

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

In C++ we have a little bit more control over the Singleton:

class Singleton {
    public:
        static Singleton& getInstance() {
            static Singleton instance;
            return instance;
        }
        Singleton(Singleton const &) = delete;
        void operator = (Singleton const&) = delete;
    private:
        Singleton() {}
}

In C++ we can just delete the = operator. This way it can't be reassigned. But as you can see the main thing with a singleton is that you have an class variable where the reference to your created singleton is stored. You just create it once and ensure that it cannot be created more than once. It you call getInstance() it either creates it, or returns the stored reference.

TL;DR

  • Only one global instance of that class is allowed
  • It provides global access to it - really handy, but sometimes weird!
  • Consider the negatives - Do you really want global access, and ONLY one instance?

If you've like this mini series please write something in the comments below :) I like hearing from you all, thanks.


Book recommendation

Design Patterns - Elements of Reusable Object-Orientated Software