The Factory Method pattern is a way of creating objects, but letting subclasses decide exactly which class to instantiate. Various subclasses might implement the interface; the Factory Method instantiates the appropriate subclass based on information supplied by the client or extracted from the current state.
Consider a high-class grocery store in London that stocks avocados all year round. It relies on a buyer to ensure that avocados arrive regularly, no matter what the time of year. The buyer sources the best avocados and supplies them to the store. The buyer is operating as a Factory Method, returning Kenyan, South African, or Spanish avocados depending on the time of year. Although the produce is labeled, the storekeeper is not particularly interested in the source of the products. Figure 5-2 shows what might happen at different times of the year.
Figure 5-2. Factory Method pattern illustration—avocado sourcing
The client declares a
variable but calls a
to instantiate it. This defers the decision as to which particular
product to create. In the UML diagram in Figure 5-3, there are two
Figure 5-3. Factory Method pattern UML diagram
The list of players is:
The interface for products ...