🔍 What is the Factory Design Pattern?
The Factory Pattern is a creational design pattern that provides an interface for creating objects in a superclass, but allows subclasses to alter the type of objects that will be created.
It’s commonly used when the exact type of the object isn't known until runtime.
✅ When Should You Use It?
- When you have a superclass with multiple subclasses, and you need to instantiate one subclass based on input or logic.
- When object creation is complex or involves logic that shouldn't be exposed to the client code.
- To follow the Open/Closed Principle — open for extension, closed for modification.
🧠 Real-World Analogy
Think of a shape drawing tool. You select "Circle", "Square", or "Rectangle" from a dropdown, and it draws it. Behind the scenes, a ShapeFactory creates the correct object depending on your input.
🧱 Structure
// 1. Product Interface
interface Shape {
void draw();
}
// 2. Concrete Products
class Circle implements Shape {
public void draw() {
System.out.println("Drawing a Circle.");
}
}
class Square implements Shape {
public void draw() {
System.out.println("Drawing a Square.");
}
}
class Rectangle implements Shape {
public void draw() {
System.out.println("Drawing a Rectangle.");
}
}
// 3. Factory Class
class ShapeFactory {
public Shape getShape(String shapeType) {
if (shapeType == null) return null;
switch (shapeType.toLowerCase()) {
case "circle": return new Circle();
case "square": return new Square();
case "rectangle": return new Rectangle();
default: throw new IllegalArgumentException("Unknown shape: " + shapeType);
}
}
}
// 4. Client Code
public class FactoryPatternDemo {
public static void main(String[] args) {
ShapeFactory shapeFactory = new ShapeFactory();
Shape shape1 = shapeFactory.getShape("Circle");
shape1.draw(); // Drawing a Circle.
Shape shape2 = shapeFactory.getShape("Square");
shape2.draw(); // Drawing a Square.
Shape shape3 = shapeFactory.getShape("Rectangle");
shape3.draw(); // Drawing a Rectangle.
}
}
🧪 Output:
Drawing a Circle.
Drawing a Square.
Drawing a Rectangle.
⚙️ UML Diagram (Text Format)
+---------------+
| Shape |<-----------------+
+---------------+ |
| +draw() | |
+---------------+ |
^ |
+------------+------------+ |
| | | |
+---------+ +---------+ +-----------+ |
| Circle | | Square | | Rectangle | |
+---------+ +---------+ +-----------+ |
| +draw() | | +draw() | | +draw() | |
+---------+ +---------+ +-----------+ |
|
+---------------------+
| ShapeFactory |
+---------------------+
| +getShape(type):Shape|
+---------------------+
🧑🏫 Key Takeaways
- Factory pattern decouples object creation logic from client code.
- Improves maintainability and scalability.
- Promotes programming to interfaces, not implementations.
Would you like to continue this series tomorrow with Builder or a different pattern from your list? I can maintain the same structure with code, diagrams, and practical clarity!