2.2.10 · HinglishDesign Principles

Design Patterns — Creational - Singleton, Factory Method, Abstract Factory, Builder, Prototype

1,886 words9 min readRead in English

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?"
Figure — Design Patterns — Creational -  Singleton, Factory Method, Abstract Factory, Builder, Prototype

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):

  1. Doosron ko instances banane se rokna hai → constructor ko private karo.
  2. Phir bhi ek dena hai → ek static method usse return karta hai.
  3. Store karna hai → ek static field 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 OS

Subclassing 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 object

End 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?
Yeh decouple karte hain kaunsa object chahiye aur kaise banta hai, creation logic centralize karke.
Singleton external instantiation kaise rokata hai?
Constructor ko private banake aur ek static getInstance() expose karke.
Naive lazy Singleton thread-safe kyun nahi hai?
Do threads dono instance == null check pass kar sakti hain aur dono instance create kar sakti hain.
Java mein best thread-safe lazy Singleton idiom kaunsa hai?
Initialization-on-demand holder (static nested class mein ek static final field ke saath).
Factory Method product ko ___ ke zariye vary karta hai?
Subclassing (creation method override karke).
Abstract Factory product family ko ___ ke zariye vary karta hai?
Composition (runtime pe ek alag factory object pass karke).
Key difference: Factory Method vs Abstract Factory?
Factory Method subclass ke zariye SIRF ek product banata hai; Abstract Factory ek object ke zariye poori matching FAMILY banata hai.
Builder kaunsa dard thik karta hai?
Telescoping constructors / bahut saare optional parameters; build() ke zariye ek immutable, validated object build karta hai.
Prototype mein often deep copy kyun zaroori hoti hai?
Shallow copy nested mutable references share karta hai, isliye ek object mutate karna uske clone ko corrupt kar deta hai.
Prototype ko constructor pe kab prefer karein?
Jab construction expensive ho ya aapke paas sirf ek runtime instance ho duplicate karne ke liye.
Singleton kabhi kabhi anti-pattern kyun hai?
Yeh global mutable state hai jo dependencies chhupata hai aur testability harm karta hai; DI prefer karo.

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.

Concept Map

decouples

replaces

includes

includes

includes

includes

includes

guarantees

risk

fix

naive lazy unsafe

subclass chooses

builds

assembles

creates by

Creational Patterns

What vs How wall

Scattered new calls

Singleton

Factory Method

Abstract Factory

Builder

Prototype

One instance + global access

Global mutable state

Prefer dependency injection

Holder idiom thread-safe

Which subclass to build

Consistent product family

Complex object step by step

Cloning existing object