Design Patterns — Creational - Singleton, Factory Method, Abstract Factory, Builder, Prototype
2.2.10· Coding › Design Principles
5 GoF creational patterns, ek saanth mein:
| Pattern | Ek-line kaam | Woh sawaal jo yeh answer karta hai |
|---|---|---|
| Singleton | Exactly ek instance, global access | "Sirf ek hi ho, yeh guarantee kaise karoon?" |
| Factory Method | Ek method jise subclasses class choose karne ke liye override karti hain | "Kaunsi subclass instantiate karoon?" |
| Abstract Factory | Related products ki ek family jo saath build hoti hai | "Kit consistent kaise rakhoon?" |
| Builder | Complex object ko step by step build karo | "Bahut zyada constructor args ho gaye?" |
| Prototype | Naaye objects kisi existing object ko clone karke create karo | "Naaya object is wale jaisa hi chahiye?" |

1. Singleton
WHY: Kuch resources naturally single hote hain — ek config registry, ek logging hub, ek connection pool. Do copies inconsistent state karengi.
HOW (first principles se derive karo):
- Doosron ko instances banane se rokna hai → constructor ko
privatekaro. - Phir bhi ek dena hai → ek
staticmethod usse return karta hai. - Store karna hai → ek
staticfield single instance ko hold karta hai.
class Logger {
private static Logger instance; // the one slot
private Logger() {} // nobody else can `new`
public static Logger getInstance() { // global access point
if (instance == null) // lazy: build on first use
instance = new Logger();
return instance;
}
}instance == null check kyun? Taaki hum lazily build karein (sirf tab jab pehli baar zarurat ho) aur sirf ek baar.
2. Factory Method
WHY: Ek Dialog jaanta hai ki use ek button chahiye, lekin WindowsDialog ko Windows button chahiye aur WebDialog ko HTML button. Base class ko new WindowsButton() nahi karna chahiye.
HOW: Direct new ko ek overridable method ke call se replace karo.
abstract class Dialog {
abstract Button createButton(); // <-- factory method (the hook)
void render() {
Button b = createButton(); // base logic, no concrete class!
b.onClick(); b.draw();
}
}
class WindowsDialog extends Dialog {
Button createButton() { return new WindowsButton(); }
}render() base class mein kyun hai? Kyunki workflow shared hai; sirf product choice vary karti hai. Yahi poora point hai — subclassing ke zariye ek decision vary karo.
3. Abstract Factory
WHY: Factory Method sirf ek product banata hai. Lekin ek Windows UI ko Windows buttons AND checkboxes AND menus chahiye — yeh sab match karne chahiye. Abstract Factory kai factory methods ko group karta hai taaki poora kit consistent rahe.
interface GUIFactory { // the family
Button createButton();
Checkbox createCheckbox();
}
class WinFactory implements GUIFactory {
public Button createButton() { return new WinButton(); }
public Checkbox createCheckbox() { return new WinCheckbox(); }
}
// client takes a GUIFactory, never knows which OSSubclassing ki jagah object (factory) kyun? Kyunki aap poori family ko runtime pe swap karte ho ek alag factory object pass karke. Factory Method subclass se vary karta hai; Abstract Factory composition se vary karta hai.
4. Builder
WHY: 8 optional parameters wala constructor → new Pizza(true,false,true,...) unreadable hai ("telescoping constructors"). Builder har step ko naam deta hai.
Pizza p = new Pizza.Builder()
.size("L")
.addCheese()
.addOlives()
.build(); // build() returns the finished, validated objectEnd mein build() kyun? Taaki object immutable aur fully validated sirf tab ho jab assembly complete ho — koi half-built objects bahar na nikal sakein.
5. Prototype
WHY: Jab construction expensive ho (heavy DB load, config parsing) ya aapke paas sirf ek runtime object ho aur duplicate chahiye ho, use clone karo.
interface Shape { Shape clone(); }
class Circle implements Shape {
int r;
public Shape clone() { Circle c = new Circle(); c.r = this.r; return c; }
}Recall Feynman: 12-saal ke bacche ko explain karo
Socho ek toy factory hai. Har baar apne haathon se har toy banana (new) ki jagah, tum machines use karte ho.
- Singleton: poore school mein ek khaas vending machine — sab log usi ek ko use karte hain.
- Factory Method: ek slot wali machine; baccha decide karta hai car nikle ya robot.
- Abstract Factory: ek machine jo hamesha matching set deti hai — red car ke saath red garage, kabhi mismatch nahi.
- Builder: ek sandwich shop jahan tum kehte ho "bread, phir cheese, phir done!" step by step.
- Prototype: ek photocopier — tumhare paas ek drawing hai aur copy press karte ho zyada paane ke liye.
Flashcards
Creational patterns kaun si problem solve karte hain?
Singleton external instantiation kaise rokata hai?
private banake aur ek static getInstance() expose karke.Naive lazy Singleton thread-safe kyun nahi hai?
instance == null check pass kar sakti hain aur dono instance create kar sakti hain.Java mein best thread-safe lazy Singleton idiom kaunsa hai?
static final field ke saath).Factory Method product ko ___ ke zariye vary karta hai?
Abstract Factory product family ko ___ ke zariye vary karta hai?
Key difference: Factory Method vs Abstract Factory?
Builder kaunsa dard thik karta hai?
build() ke zariye ek immutable, validated object build karta hai.Prototype mein often deep copy kyun zaroori hoti hai?
Prototype ko constructor pe kab prefer karein?
Singleton kabhi kabhi anti-pattern kyun hai?
Connections
- Design Principles — patterns SOLID in action hain (khaaskar Open/Closed aur Dependency Inversion).
- Factory Method ek special case hai jo andar Abstract Factory mein use hota hai.
- Builder vs Prototype — fresh build karo vs existing copy karo.
- Singleton aksar Abstract Factory ke saath combine hota hai (ek global factory).
- Structural Patterns aur Behavioral Patterns — GoF ki baaki do categories.
- Dependency Injection — Singleton ka modern alternative.