Pattern to creating objects
Singleton
This pattern is used to ensure only one instant exists.
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
Clones instances for a prototypical instance.
Builder
Construct object step by step.
Factory
Delegate object instantiation to subclasses.
AbstractFactory
Creates related object families without specifying their concrete classes.
Last updated