The Factory Pattern is a creational design pattern that provides an interface for creating objects but allows subclasses or dedicated factory classes to alter the type of objects that will be created.
Example: Factory Pattern with Shape
Step 1: Create a common interface
public interface Shape {
void draw();
}
Step 2: Implement 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");
}
}
Step 3: Create the Factory class
public class ShapeFactory {
// Factory method
public Shape getShape(String shapeType) {
if (shapeType == null) {
return null;
}
switch (shapeType.toLowerCase()) {
case "circle":
return new Circle();
case "rectangle":
return new Rectangle();
case "square":
return new Square();
default:
throw new IllegalArgumentException("Unknown shape type: " + shapeType);
}
}
}
Step 4: Use the Factory in your client code
public class FactoryPatternDemo {
public static void main(String[] args) {
ShapeFactory shapeFactory = new ShapeFactory();
Shape circle = shapeFactory.getShape("circle");
circle.draw(); // Output: Drawing a Circle
Shape rectangle = shapeFactory.getShape("rectangle");
rectangle.draw(); // Output: Drawing a Rectangle
Shape square = shapeFactory.getShape("square");
square.draw(); // Output: Drawing a Square
}
}
Key Points:
- The client code (
FactoryPatternDemo
) does not instantiate objects directly. - Instead, it asks the factory (
ShapeFactory
) to create them. - This makes it easier to add new shapes later without changing client code.