O'Reilly logo

C# 3.0 Design Patterns by Judith Bishop

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 products ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required