Singleton Pattern

In every application there is a need in some kind of globally accessible element that all other components can refer to. Configuration, for instance, is one of those important elements. Multiple classes and functions can refer to it at different points in time to base their output on a certain active configuration attribute. A lot of applications rely on this kind of structure, and it is important to provide a stable and robust solution to this case.

Many languages offer such features as declaring particular variables or function global, therefore making them accessible from anywhere in the code. And why not? It is very convenient when you can get a particular variable on a whim from any class or function. However, it poses several threats to the overall concept of a robust application. You might have heard that Global state is sometimes called Evil. Among many reasons, inability to unit test a particular component is one of them. Since the component relies on a global state, which is also referred to by other components, thus is unpredictable, it makes it very difficult to test this piece of code separately from the global context and be sure that the function will always result in a certain output based on a certain input. Our input remain uncertain.

On top of that there are more issues with global state. What if the global variable being accessed and modified by two different components at the same time? That brings out even more uncertainty, and a lot more errors that are not that easy to identify. What if the global variable is instantiated multiple times? There are a lot of questions that need to be addressed.

What is the best way to remedy the global state? We still very much in need of some structure that all of the application can have safe access to. That’s where Singleton Pattern comes on stage.


The Singleton Pattern:

ensures a class has only one instance, and provides a global point of access to it.


Singleton makes sure that it is one and only of its kind by keeping a private and static instance of itself, and making constructor of the class private too, so that no one else but the class itself can instantiate it. The point of access is a publicly accessible and static method that either returns the instance that is stored inside the class, or if the instance is absent, creates one, and then returns it to the callers.

// Example in Java
// Source: https://en.wikipedia.org/wiki/Singleton_pattern
public final class Singleton {

    private static final Singleton INSTANCE = new Singleton();

    private Singleton() {}

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

Here are several things that Singleton accomplishes successfully:

  • First, it makes sure that there is only one instance of itself. You can’t create a second one, and that’s good. We can be sure in its state.
  • Second, it makes itself globally accessible through its public static method. All components can refer to this instance, and operate out of confidence that this instance is one and only.

There are a couple of intricacies that we need to be aware though. If the application utilizes multithreading approach, it needs to deal with the Singleton appropriately. If calls to Singleton are not synchronized with other callers, we can run into the same problem we have seen earlier – no certainty in state and input/output. Look out for this if you are programming your application to be thread-safe by making sure to apply proper handling in the language you choose. Here are a couple of guidelines:

  • If performance is not important, the class is small, and you do not do a lot of heavy processing, just leave it be. As funny as it sounds, that is one of the examples when not pursuing the perfection is the right strategy.
  • Instantiate your Singleton eagerly instead of lazily. Create an instance of singleton even before it gets to be dealt with through the public accessor. This would guarantee that the instance will be created before anyone will get to access it.
  • Use Double-Checked Locking. What it means is you first see if an instance is created, and then if not, you synchronize. With this approach you only are going to synchronize one time – at instantiation. After that it will be available to everyone.
// Example of thread-safe, lazily instantiated Singleton in Java
// Source: https://en.wikipedia.org/wiki/Singleton_pattern
public final class Singleton {

    private static volatile Singleton instance = null;

    private Singleton() {}

    public static Singleton getInstance() {
        if (instance == null) {
            synchronized(Singleton.class) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }

        return instance;
    }
}

Singleton is a very useful pattern that is used in many applications. A lot of MVC frameworks have some kind of Singleton implementation ready for programmers to use. This pattern allows us to avoid a lot of problems that we can get in case we decide to use global state.

One thought on “Singleton Pattern

Leave a comment