The Factory Method defines a method, which should be used for creating objects instead of using a direct constructor call (new
operator). It provides an interface for creating objects and allows subclasses to alter the type of object that will be created.
Applicability
- You need to support multiple product variations
- You want to add new product types without modifying existing code
- The object creational logic is wanted to be centralised
Approach
- Define an interface for creating an object, so called creator interface
- Implement concrete creator classes which create a specific type of product
- In client code, use the creator interface and its factory method to create products without knowing the specific concrete product classes. (AKA Virtual Constructor)
Components
- Product (abstract)
- Defines an interface of objects the factory method creates
- Concrete product
- Implements the product interface
- Creator (abstract)
- Declares the factory method, which returns an object of type product
- Concrete creator
- Overrides the factory method to return an instance of the concrete product
Example
Identify factory method components
Product: Shape
Concrete product: Rectangle
, Circle
Creator: ShapeCreator
Concrete creator: RectangleCreator
, CircleCreator
Product
Shape
is an abstract product that defines the the common interface for all products. It declares common behaviours of its products.
public interface Shape {
void draw();
}
Concrete product
Concrete product implements the abstract product.
class Rectangle extends Shape {
@Override
void draw() {
System.out.println("Drawing a Rectangle");
}
}
class Circle extends Shape {
@Override
void draw() {
System.out.println("Drawing a Circle");
}
}
Creator
The creator is an interface that declares the factory method createShape()
// Abstract Creator: ShapeCreator
interface ShapeCreator {
Shape createShape();
}
Concrete creator
Concrete creators provides their own implementation of creator interface.
// Concrete Creators: RectangleCreator and CircleCreator
class RectangleCreator implements ShapeCreator {
@Override
public Shape createShape() {
return new Rectangle();
}
}
class CircleCreator implements ShapeCreator {
@Override
public Shape createShape() {
return new Circle();
}
}
Client
public class Main {
public static void main(String[] args) {
// Create concrete creators
ShapeCreator rectangleCreator = new RectangleCreator();
ShapeCreator circleCreator = new CircleCreator();
// Use the factory methods to create shapes
Shape rectangle = rectangleCreator.createShape();
Shape circle = circleCreator.createShape();
// Draw the shapes
rectangle.draw();
circle.draw();
}
}
Back to parent page: Creational Patterns
Design_Pattern Creational_Design_Patterns SOFT2201 Factory_Method_Pattern