Factory Pattern की जानकारी
In this page:
function factory(kind: "a" | "b"): Product {
switch (kind) {
case "a": return new ProductA();
case "b": return new ProductB();
}
}
Factory Function
एक factory function इस pattern का सबसे simple रूप है — एक typed function जो कुछ input लेती है और एक पूरी तरह से constructed object return करती है, object के construction details को एक single call के पीछे छिपाते हुए।
उदाहरण: Factory Function
interface User {
name: string;
}
function createUser(name: string): User {
return { name };
}
console.log(createUser("Ravi"));
Interface के साथ Factory
एक interface के against typed एक factory गारंटी देती है कि यह produce करने वाली हर object उस interface के shape को satisfy करती है, भले ही factory internally scenes के पीछे कई अलग concrete implementations बनाए।
उदाहरण: Factory with Interface
interface Shape {
area(): number;
}
function createSquare(side: number): Shape {
return { area: () => side * side };
}
console.log(createSquare(4).area());
Factory Class
एक factory class related creation logic को methods में group करती है, जो उपयोगी है जब एक object construct करने के लिए कई steps चाहिए या factory खुद calls के बीच रखे shared internal state पर depend करता है।
उदाहरण: Factory Class
class WidgetFactory {
private count = 0;
create(name: string) {
this.count++;
return { id: this.count, name };
}
}
const factory = new WidgetFactory();
console.log(factory.create("Button"));
Configuration-Based Creation
Configuration-based creation का मतलब है factory एक passed-in option (जैसे एक type: circle | square field) के आधार पर यह चुनता है कि कौन सा concrete type construct करना है, उस branching logic को बिखरने के बजाय एक जगह centralize करते हुए।
उदाहरण: Configuration-Based Creation
interface Shape { area(): number; }
function createShape(type: "circle" | "square", size: number): Shape {
if (type === "circle") return { area: () => Math.PI * size * size };
return { area: () => size * size };
}
console.log(createShape("circle", 2).area());
Factory कब उपयोग करें
Factory pattern तब अपनाएं जब object creation में meaningful decision logic या setup steps शामिल हों — किसी भी असली construction complexity न रखने वाले plain object के लिए, एक factory value जोड़े बिना सिर्फ indirection जोड़ता है।
उदाहरण: When to Use Factory
interface Shape { area(): number; }
function createShape(type: "circle" | "square", size: number): Shape {
return type === "circle"
? { area: () => Math.PI * size * size }
: { area: () => size * size };
}
console.log(createShape("square", 3).area());
- एक object return करना जो interface को satisfy नहीं करता, जैसे
area()missing हो। - एक factory function पर
newउपयोग करना, जब factories normally call होती हैं। - Factory से
anyreturn करना, इसलिए callers specific type खो देते हैं।
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: