DEV Community

Poorna Senani Gamage
Poorna Senani Gamage

Posted on

3 2

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;
    }
}

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay