Defines an interface for creating an object, but lets subclasses decide which class to instantiate, allowing a class to defer instantiation to subclasses. Use it when a class cannot anticipate the class of objects it must create, when it wants subclasses to specify the objects it creates, or when classes delegate responsibility to one of several helper subclasses.
Examples:
- A logistics app initially ships only trucks. When sea transport is needed, instead of scattering new Ship constructors throughout the codebase, a factory method in each logistics subclass (RoadLogistics, SeaLogistics) creates the appropriate transport object — trucks or ships — while the rest of the code works only against the common Transport interface.
// Creator declares factory method; subclasses override it
class MazeGame {
public:
virtual Room* MakeRoom(int n) const { return new Room(n); }
virtual Wall* MakeWall() const { return new Wall; }
Maze* CreateMaze();
};
// Concrete creator overrides to vary the product
class BombedMazeGame : public MazeGame {
public:
Room* MakeRoom(int n) const override { return new RoomWithABomb(n); }
Wall* MakeWall() const override { return new BombedWall; }
};
Synonyms: virtual constructor