Interview question
What is the Factory design pattern and when should you use it? Factory design pattern क्या है और कब use करना चाहिए?
Answer
The Factory pattern encapsulates object creation logic in a dedicated method or class, so client code depends on an interface/abstract type rather than concrete classes - useful when object creation involves conditional logic or varies by input.
// Common interface for products
interface Shape {
void draw();
}
class Circle implements Shape {
public void draw() { System.out.println('Drawing Circle'); }
}
class Square implements Shape {
public void draw() { System.out.println('Drawing Square'); }
}
class Rectangle implements Shape {
public void draw() { System.out.println('Drawing Rectangle'); }
}
// Factory - centralizes creation logic
class ShapeFactory {
public static Shape createShape(String type) {
switch (type.toLowerCase()) {
case 'circle': return new Circle();
case 'square': return new Square();
case 'rectangle': return new Rectangle();
default: throw new IllegalArgumentException('Unknown shape: ' + type);
}
}
}
// Client code doesn't need to know concrete classes
Shape shape1 = ShapeFactory.createShape('circle');
shape1.draw(); // Drawing Circle
Shape shape2 = ShapeFactory.createShape('square');
shape2.draw(); // Drawing Square
// Benefits:
// - Adding a new shape type only requires changing the Factory,
// not every place that creates shapes
// - Client code depends on the Shape interface, not concrete classes
// (Dependency Inversion Principle)
// Real-world Java examples of the Factory pattern:
// Calendar.getInstance(), NumberFormat.getInstance(),
// java.sql.DriverManager.getConnection() (Abstract Factory variant)Factory pattern object creation logic को एक dedicated method/class में encapsulate करता है, ताकि client code concrete classes की बजाय interface/abstract type पर depend करे - जब object creation में conditional logic हो तब उपयोगी है।
interface Shape {
void draw();
}
class Circle implements Shape {
public void draw() { System.out.println('Drawing Circle'); }
}
class Square implements Shape {
public void draw() { System.out.println('Drawing Square'); }
}
class ShapeFactory {
public static Shape createShape(String type) {
switch (type.toLowerCase()) {
case 'circle': return new Circle();
case 'square': return new Square();
default: throw new IllegalArgumentException('Unknown shape: ' + type);
}
}
}
Shape shape1 = ShapeFactory.createShape('circle');
shape1.draw(); // Drawing Circle
Shape shape2 = ShapeFactory.createShape('square');
shape2.draw(); // Drawing Square
// फायदे:
// - नया shape type सिर्फ Factory में add करना पड़ता है
// - Client code Shape interface पर depend करता है, concrete classes पर नहीं
// Real-world उदाहरण: Calendar.getInstance(), NumberFormat.getInstance()Was this answer clear?