Java का Factory Pattern
In this page:
interface Product { }
class Factory {
static Product create(String type) {
// return a new ConcreteProduct based on type
}
}
What is the Factory Pattern?
Factory Pattern किसी object को बनाने के लिए एक interface, या एक abstract method, define करता है, लेकिन subclasses को तय करने देता है कि असल में कौन सी concrete class instantiate होती है। यह calling code को interface के खिलाफ ही काम करता रखता है, बिना यह जाने कि यह आखिरकार कौन सा implementation पाता है।
उदाहरण: What is the Factory Pattern?
public class Main {
interface Shape {}
static class Circle implements Shape {}
interface ShapeFactory { Shape create(); }
public static void main(String[] args) {
ShapeFactory factory = Circle::new; // caller only knows the interface
Shape shape = factory.create();
System.out.println(shape.getClass().getSimpleName());
}
}
Login to try C/C++/Java/PHP code in the editor
Polymorphic Factory Method
किसी abstract class के अंदर एक factory method implement करके और उसे वहां abstract छोड़कर, हर subclass उस method को override करके specify कर सकती है कि उसके particular variant के लिए कौन सी concrete class बनती है, object-creation logic को subclass के बाकी behavior के साथ polymorphically बदलने देते हुए।
उदाहरण: Polymorphic Factory Method
public class Main {
static abstract class Dialog {
abstract Object createButton(); // subclasses decide the concrete type
}
static class WindowsDialog extends Dialog {
Object createButton() { return "WindowsButton"; }
}
public static void main(String[] args) {
Dialog dialog = new WindowsDialog();
System.out.println(dialog.createButton());
}
}
Login to try C/C++/Java/PHP code in the editor
Parameterized Factory Method
आप किसी factory को parameterize कर सकते हैं ताकि यह input value, जैसे type code या name, के आधार पर अलग-अलग object types return करे, बजाय हर variant के लिए एक अलग factory method चाहिए के। उस parameter के लिए raw String या int के बजाय एक enum का उपयोग करना जोरदार रूप से recommended है क्योंकि यह invalid values को compile time पर पकड़ता है।
उदाहरण: Parameterized Factory Method
public class Main {
enum ShapeType { CIRCLE, SQUARE }
static Object createShape(ShapeType type) {
return switch (type) { // enum catches invalid values at compile time
case CIRCLE -> "Circle";
case SQUARE -> "Square";
};
}
public static void main(String[] args) {
System.out.println(createShape(ShapeType.SQUARE));
}
}
Login to try C/C++/Java/PHP code in the editor
Benefits of Decoupling
Factory Pattern का मुख्य फायदा client code को उन exact classes से decouple करना है जिन पर यह instantiate होने के लिए निर्भर है। Clients object-creation complexity से पूरी तरह सुरक्षित हैं, चाहे वह complexity subclasses में से चुनना हो, configuration पढ़ना हो, या dependencies wire करना हो।
उदाहरण: Benefits of Decoupling
public class Main {
interface Notifier { void send(String msg); }
static class EmailNotifier implements Notifier {
public void send(String msg) { System.out.println("Email: " + msg); }
}
static Notifier createNotifier() { return new EmailNotifier(); } // client shielded from creation details
public static void main(String[] args) {
Notifier n = createNotifier();
n.send("Hello");
}
}
Login to try C/C++/Java/PHP code in the editor
Real-World Use Cases
Factories असली systems में लगातार दिखती हैं: किसी settings file से configured database connection load करना, runtime पर कोई communication protocol implementation चुनना, या user preference के आधार पर कोई specific notification channel (email, SMS, push) चुनना, ये सभी इस pattern के लिए स्वाभाविक fits हैं।
उदाहरण: Real-World Use Cases
// Define the class Main
public class Main {
// Define the interface Notifier
interface Notifier { void send(String msg); }
// Define the class SmsNotifier
static class SmsNotifier implements Notifier {
public void send(String msg) { System.out.println("SMS: " + msg); }
}
static class EmailNotifier implements Notifier {
public void send(String msg) { System.out.println("Email: " + msg); }
}
static Notifier getNotifier(String preference) {
return preference.equals("sms") ? new SmsNotifier() : new EmailNotifier();
}
// Program entry point: the JVM starts running here
public static void main(String[] args) {
getNotifier("sms").send("Order shipped");
}
}
Login to try C/C++/Java/PHP code in the editor
- client code में अभी भी
new Circle()लिखना, जो factory का concrete class छुपाने का पूरा मकसद हटा देता है। - factory method को
Shapeinterface के बजाय concrete class return करवाना, जिससे callers फिर भी उस पर निर्भर रहते हैं। - किसी parameterized factory में अज्ञात type के लिए
nullreturn करना, जो बाद मेंNullPointerExceptionका कारण बनता है; इसके बजाय एकIllegalArgumentExceptionफेंकें।
Chapter Quiz — Complete all 14 topics to unlock
0/14 topics done
Complete these topics first:
- Java Design Patterns Introduction
- Java Singleton Pattern
- Java Factory Pattern
- Java Observer Pattern
- Java Builder Pattern
- Java MVC Architecture
- Java Adapter Pattern
- Java Decorator Pattern
- Java Strategy Pattern
- Java Command Pattern
- Java Facade Pattern
- Java Proxy Pattern
- Java Template Method Pattern
- Java Repository Pattern