Ensure a class has only one instance and provide a global point of access to it.
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;
}
}
Output
Objects are the same instance
Top comments (0)