← Back to Advanced Java Course | Chapter 6: Design Patterns | Lesson 3 of 14

Java का Factory Pattern

Factory pattern एक खास maker है जो आपके लिए objects बनाता है, जैसे खुद bake किए बिना pizza order करना। आप एक type मांगते हैं, और यह सही वाला सौंप देता है।
Syntax
java
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?

java
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());
	}
}

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

java
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());
	}
}

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

java
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));
	}
}

Benefits of Decoupling

Factory Pattern का मुख्य फायदा client code को उन exact classes से decouple करना है जिन पर यह instantiate होने के लिए निर्भर है। Clients object-creation complexity से पूरी तरह सुरक्षित हैं, चाहे वह complexity subclasses में से चुनना हो, configuration पढ़ना हो, या dependencies wire करना हो।

उदाहरण: Benefits of Decoupling

java
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");
	}
}

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

java
// 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");
	}
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. client code में अभी भी new Circle() लिखना, जो factory का concrete class छुपाने का पूरा मकसद हटा देता है।
  2. factory method को Shape interface के बजाय concrete class return करवाना, जिससे callers फिर भी उस पर निर्भर रहते हैं।
  3. किसी parameterized factory में अज्ञात type के लिए null return करना, जो बाद में NullPointerException का कारण बनता है; इसके बजाय एक IllegalArgumentException फेंकें।

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.