Singleton Design Pattern

Singleton Pattern is probably the most widely used design pattern. It is a simple pattern, easy to understand and to use. It ensures a class only has one instance, and provides a global point of access to it.

Table of Content

  1. Uses
  2. Initialization Types of Singleton
  3. Implementation

Uses

Use the Singleton method Design Pattern when:

Initialization Types of Singleton

Singleton class can be instantiated by two methods:

Implementation

alt text

/*package whatever //do not write package name here */
import java.io.*;

class Singleton {
    // static class
    private static Singleton instance;

    private Singleton(){
        System.out.println("Singleton is Instantiated.");
    }

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

    public static void doSomething(){
        System.out.println("Somethong is Done.");
    }
}

class GFG {
    public static void main(String[] args)
    {
        Singleton.getInstance().doSomething();
    }
}