Pattern to creating objects
Singleton
class SingleTon {
private static SingleTon instance;
private SingleTon() {
}
public static SingleTon getInstance() {
if (instance == null) {
synchronized(SingleTon.class) {
if (instance == null) {
instance = new SingleTon();
}
}
}
return instance;
}
}
class SingleTon2 {
private static SingleTon2 singleton = new SingleTon2();
private SingleTon2() {
}
public static SingleTon2 getInstance() {
return singleton;
}
}
public class Main {
public static void main(String[] args) {
// Get the singleton instance
Singleton singleton1 = Singleton.getInstance();
Singleton singleton2 = Singleton.getInstance();
// Both references point to the same instance
System.out.println(singleton1 == singleton2); // Output: true
}
}
Prototype
Builder
Factory
AbstractFactory
Last updated