DEV Community

Cover image for Singleton Pattern
eidher
eidher

Posted on • Edited on

1 1

Singleton Pattern

Ensure a class has only one instance and provide a global point of access to it.

Alt Text

Participants

  • Singleton: defines an Instance operation that lets clients access its unique instance. Instance is a class operation. Responsible for creating and maintaining its own unique instance.

Code

public class Main {

    public static void main(String[] args) {
        Singleton s1 = Singleton.instance();
        Singleton s2 = Singleton.instance();
        if (s1 == s2) {
            System.out.println("Objects are the same instance");
        }
    }
}

public class Singleton {
    private static Singleton instance;

    protected Singleton() {
    }

    public static Singleton instance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}
Enter fullscreen mode Exit fullscreen mode

Output

Objects are the same instance
Enter fullscreen mode Exit fullscreen mode

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up