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.
Concrete product
Concrete product implements the abstract product.
Creator
The creator is an interface that declares the factory method createShape()
Concrete creator
Concrete creators provides their own implementation of creator interface.
Client
Design_PatternCreational_Design_Patterns SOFT2201Factory_Method_Pattern