Factory Method Pattern

Role

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.

Illustration

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.

Factory Method pattern illustration—avocado sourcing

Figure 5-2. Factory Method pattern illustration—avocado sourcing

Design

The client declares a Product variable but calls a FactoryMethod 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 choices: ProductA and ProductB.

Factory Method pattern UML diagram

Figure 5-3. Factory Method pattern UML diagram

The list of players is:

IProduct

The interface for ...

Get C# 3.0 Design Patterns now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.