DEV Community 👩‍💻👨‍💻

Poorna Senani Gamage
Poorna Senani Gamage

Posted on

Singleton Pattern

Singleton pattern is the simplest pattern in java and is under the creational pattern. some key points to use in singleton pattern.

  • It is static in nature
  • private constructor
  • private static instance of the class
  • public static getter method
  • no parameters to the constructor

create singleton class

public class Singleton {
    private static Singleton object = null;
    private Singleton() {
    }
    public static Singleton getInstance() {
        if (object == null) {
            object = new Singleton();
        }
        return object;
    }
    public void showMessage() {
        System.out.println("Singleton Pattern");
    }
}

create demo class

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

but this classic implementation not thread safe. therefore using synchronized make sure that the one thread can execute the getInstance();at one time.
As this;

public class Singleton {
    private static Singleton object = null;
    private Singleton() {
    }
    public static synchronized Singleton getInstance() {
        if (object == null) {
            object = new Singleton();
        }
        return object;
    }
}

Top comments (0)

👋 Have You Posted on DEV Yet?

Head over to our Welcome Thread and tell us a bit about yourself!