Singleton Pattern

The singleton pattern is a creational design pattern that is used to restricts the instantiation of a class to one object. This pattern becomes useful when exactly one object is needed to coordinate actions across the system. For example when there is situation to create the communication with database only one way, then it comes handy to use this pattern. 

This pattern has been used to create other design pattern like Abstract Factory, Builder Design Pattern, Prototype Design Pattern and Facade Design Pattern.

More importantly, the state object are often singletons.

 

Structure

The Structure of the singleton pattern is shown below:

singleton pattern

Figure: UML for Singleton Pattern

There are two principles in order to make implementation of a singleton pattern.

  • First is that there must a single instance of the class and
  • Second is that there must be mechanism for global access.

So, there must be a mechanism to access the singleton class member without creating a class object and a mechanism to persist the value of class members among class objects.

The implementation of the singleton pattern has a class with a method that creates a new instance of the class if one does not exist. If an instance already exists, it simply returns a reference to that object. The constructor is made private to make sure that the object cannot be instantiated any other way.

 

Java Implementation

Here is an example of the Singleton Pattern implemented in Java.

SingleObject is a class that has private constructor and static method that provides the instance of the class.

public class SingleObject {
    private static SingleObject singleObject;

    private SingleObject(){}

    public static SingleObject getInstance(){
        if(singleObject == null){
            singleObject= new SingleObject();
        }
        return singleObject;
    }

    public void showMessage(){
        System.out.println("Instance is created...");
    }
}

class SingletonDemo{
    public static void main(String[] args) {
        SingleObject object=SingleObject.getInstance();
        object.showMessage();
    }
}

The ouput of the above program is:

Instance is created...

One of the trickiest part we need to understand here is the distinction between a simple static instance of a class and a singleton. The main difference is that singleton can also be lazily constructed even though it can be implemented as a static instance, requiring no memory or resources until needed.

Design Patterns Introduction
Observer Pattern