Creational patterns deal with object creation mechanisms, trying to create objects in a manner suitable to the situation. Instead of instantiating objects directly using new
.
1. Singleton Pattern

Ensures a class has only one instance and provides a global point of access.
public class Singleton {
private static Singleton instance;
private Singleton() {}
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
2. Factory Method Pattern

Defines an interface for creating an object but lets subclasses alter the type of objects that will be created.
interface Product {
void use();
}
class ConcreteProductA implements Product {
public void use() { System.out.println("Using Product A"); }
}
class Creator {
public Product factoryMethod(String type) {
if (type.equals("A")) {
return new ConcreteProductA();
}
return null;
}
}
3. Abstract Factory Pattern

Provides an interface for creating families of related or dependent objects without specifying their concrete classes.
interface GUIFactory {
Button createButton();
Checkbox createCheckbox();
}
class WinFactory implements GUIFactory {
public Button createButton() { return new WinButton(); }
public Checkbox createCheckbox() { return new WinCheckbox(); }
}
Use when your system needs to be independent of how its objects are created.
4. Builder Pattern

Separates the construction of a complex object from its representation, allowing the same construction process to create different representations.
class Computer {
String CPU;
String GPU;
static class Builder {
private String CPU;
private String GPU;
Builder setCPU(String cpu) { this.CPU = cpu; return this; }
Builder setGPU(String gpu) { this.GPU = gpu; return this; }
Computer build() {
Computer c = new Computer();
c.CPU = this.CPU;
c.GPU = this.GPU;
return c;
}
}
}
Use when you need to build a complex object step by step.
5. Prototype Pattern

Creates new objects by copying an existing object, known as the prototype.
class Prototype implements Cloneable {
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
Use when object creation is expensive and cloning gives better performance.
That’s all for today’s post — feel free to leave a comment and join the discussion!