📘 Lesson  ·  Lesson 47

Singleton Pattern

What is Singleton?

The Singleton pattern ensures a class has only ONE instance in the whole program — used for things like a database connection or config.

Singleton Example

class Database {
    private static Database instance;
    private Database() {}                 // private constructor
    public static Database getInstance() {
        if (instance == null) {
            instance = new Database();
        }
        return instance;
    }
}
Database db1 = Database.getInstance();
Database db2 = Database.getInstance();
System.out.println(db1 == db2);   // true (same instance)
true

Summary

  • Singleton = one instance only, via a private constructor + getInstance().
  • Used for shared resources like config or DB connections.

Singleton क्या है?

Singleton pattern सुनिश्चित करता है कि class का पूरे program में सिर्फ एक instance हो — database connection या config जैसी चीज़ों के लिए।

Singleton Example

class Database {
    private static Database instance;
    private Database() {}                 // private constructor
    public static Database getInstance() {
        if (instance == null) {
            instance = new Database();
        }
        return instance;
    }
}
Database db1 = Database.getInstance();
Database db2 = Database.getInstance();
System.out.println(db1 == db2);   // true (same instance)
true

सारांश

  • Singleton = सिर्फ एक instance, private constructor + getInstance() से।
  • Config या DB connections जैसे shared resources के लिए।
← Back to Java Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

💻 लाइव कोड एडिटर

इस पेज के प्रोग्राम यहीं तैयार हैं — चलाएँ, बदलें और सीखें। कुछ भी इंस्टॉल किए बिना।
OneCompiler द्वारा संचालित। कोड एडिटर में अपने आप आ जाता है — Run दबाकर आउटपुट देखें। अगर एडिटर न खुले तो नए टैब में खोलें.