Dezign Patterns
Factory Design Pattern
The Factory Pattern defines an interface for creating objects, but allows subclasses to alter the type of objects that will be created.
I - Interface
public interface Shape {
void draw();
}
II - Concrete classes
public class Circle implements Shape {
@Override
public void draw() {
System.out.println("Drawing a Circle");
}
}
public class Rectangle implements Shape {
@Override
public void draw() {
System.out.println("Drawing a Rectangle");
}
}
public class Square implements Shape {
@Override
public void draw() {
System.out.println("Drawing a Square");
}
}
III - Factory class
public class ShapeFactory {
// Factory method
public Shape getShape(String shapeType) {
if (shapeType == null) {
return null;
}
if (shapeType.equalsIgnoreCase("CIRCLE")) {
return new Circle();
} else if (shapeType.equalsIgnoreCase("RECTANGLE")) {
return new Rectangle();
} else if (shapeType.equalsIgnoreCase("SQUARE")) {
return new Square();
}
return null;
}
}
IV - Client Code
public class FactoryPatternDemo {
public static void main(String[] args) {
ShapeFactory shapeFactory = new ShapeFactory();
// Get an object of Circle and call draw
Shape shape1 = shapeFactory.getShape("CIRCLE");
shape1.draw();
// Get an object of Rectangle and call draw
Shape shape2 = shapeFactory.getShape("RECTANGLE");
shape2.draw();
// Get an object of Square and call draw
Shape shape3 = shapeFactory.getShape("SQUARE");
shape3.draw();
}
}
✅ Advantages of Factory Pattern
- Decouples client code from object creation logic.
- Makes it easy to introduce new product types without modifying existing code (Open/Closed Principle).
- Centralizes control of object instantiation.
❌ Disadvantages of the Factory Pattern
- Increased Code Complexity
You often end up creating additional classes (factories, product interfaces, etc.), which can make the project harder to navigate for simple use cases. - Less Transparency
It hides the concrete class being instantiated, which might confuse developers unfamiliar with the pattern or when debugging. - Difficult to Extend with Many Variants
As the number of product types grows, the factory method can become a large if-else or switch statement, which violates the Open/Closed Principle if not refactored. - Tight Coupling to Factory
Although the client is decoupled from specific classes, it is still tightly coupled to the factory. Changing the factory may require changes in many parts of the application. - May Encourage God Objects
A single factory responsible for creating too many object types can become bloated and hard to maintain. - Dependency Management Challenges
You might still need dependency injection or service locators to manage object creation if dependencies are complex.