Creational design patterns provide various object creation mechanisms, which increase flexibility and reuse of existing code.
graph TD
A[Creational Patterns] --> B[Factory Method]
A --> C[Abstract Factory]
A --> D[Builder]
A --> E[Prototype]
A --> F[Singleton]
B --> G[Creates objects through inheritance]
C --> H[Creates families of related objects]
D --> I[Constructs complex objects step by step]
E --> J[Creates objects by cloning]
F --> K[Ensures a single instance]
| Pattern | Creation Method | Flexibility | Complexity | Common Use Cases |
|---|---|---|---|---|
| Factory Method | Inheritance | High | Low | Framework extensions |
| Abstract Factory | Composition | Very High | Medium | Platform independence |
| Builder | Step-by-step | High | Medium | Complex object creation |
| Prototype | Cloning | Medium | Low | Object copying |
| Singleton | Static | Low | Low | Shared resources |
// Creator
public abstract class DocumentCreator {
public abstract Document createDocument();
public void processDocument() {
Document doc = createDocument();
doc.process();
}
}
// Concrete Creator
public class PDFDocumentCreator extends DocumentCreator {
@Override
public Document createDocument() {
return new PDFDocument();
}
}
// Abstract Factory
public interface GUIFactory {
Button createButton();
Checkbox createCheckbox();
}
// Concrete Factory
public class WindowsFactory implements GUIFactory {
@Override
public Button createButton() {
return new WindowsButton();
}
@Override
public Checkbox createCheckbox() {
return new WindowsCheckbox();
}
}
// Builder
public class ComputerBuilder {
private Computer computer = new Computer();
public ComputerBuilder addProcessor(String processor) {
computer.setProcessor(processor);
return this;
}
public ComputerBuilder addMemory(int memory) {
computer.setMemory(memory);
return this;
}
public Computer build() {
return computer;
}
}
// Usage
Computer computer = new ComputerBuilder()
.addProcessor("Intel i7")
.addMemory(16)
.build();
// Prototype
public abstract class Shape implements Cloneable {
private String id;
protected String type;
@Override
public Object clone() {
Object clone = null;
try {
clone = super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return clone;
}
}
// Concrete Prototype
public class Rectangle extends Shape {
public Rectangle() {
type = "Rectangle";
}
}
// Thread-safe Singleton
public class Singleton {
private static volatile Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}