Singleton Design Pattern

The Singleton pattern assures that a class has only one instance and provides a global point of access for it. Sometimes, singleton patterns is considered as the antipattern because high usage of this can have more cons than the pros. There are two types of singleton pattern:

  1. Lazy Instantiation: Instances of class are created only when required. The benefit of this pattern is that the class will only be instantiated when it will be required.
  2. Early Instantiation: Instances of class are created right at the class loading. The main drawback here is that the class will still be loaded even if it is not used.

Key points of singleton pattern

  1. There must be one single instance of a class at any point of the application and must be accessible from a global point of access.
  2. The singleton classes contains static members. This usage of the static variables ensures that the memory will be allocated only once in the heap, making the class have only a single member.
  3. These classes always have a private type constructor so that no new objects are created every-time when we try to instantiate objects of the class.
  4. All Singleton classes should have a static type of getter method for the class instance. This acts as the global point of access for the instance. This getter method are referred to as the factory method.
  5. Singleton classes are used mostly for database connection objects, logger objects etc where only one class is required.

Singleton Class Java Implementation

public class Singleton {
    private static Singleton instance;

    private Singleton() {
        // private constructor to prevent instantiation
    }

    public static Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}

In the above code we can see that the class Singleton prevents instantiation of it’s objects via the constructor and allows only one instance to be present via the factory method getInstance(). The method will create an instance if no instance is created else it will return the previously created instance.

For multi-threaded applications we sometimes could also use synchronized keyword for the getInstance() factory method. The usage of this keyword ensures, only one thread can execute this factory method at a specific point of time.

Apart from the singleton design patterns, there are more design patterns used in computer science. You can read more about them here.

Leave a Comment