Factory method pattern

Rather than by calling a constructor, this is accomplished by invoking a factory method to create an object.

[1] The factory method design pattern solves problems such as: This enables the creation of subclasses that can change the way in which an object is created (for example, by redefining which class to instantiate).

According to Design Patterns: Elements of Reusable Object-Oriented Software: "Define an interface for creating an object, but let subclasses decide which class to instantiate.

MagicMazeGame and OrdinaryMazeGame are subclasses of MazeGame implementing the factory method producing the final products.

Factory methods thus decouple callers (MazeGame) from the implementation of the concrete classes.

Custom logic could run after the object is obtained in the concrete factory method.

The factory method can also be defined as publicand called directly by the client code (in contrast to the previous Java example).

A sample UML class diagram for the Factory Method design pattern. [ 4 ]