The Factory Method Pattern
The Factory Method pattern allows you to abstract the creation of objects, specifying the class of the object at runtime rather than at design time. It accomplishes this by defining a separate method for creating objects (see Figure 8-19). Subclasses can then override the creation method to specify the type of derived object to create, as needed (you can think of it as a "just-in-time inventory" for software). The term "factory" is loosely used to refer to any method whose main purpose is the creation of objects.
Factory methods are most commonly found in toolkits and frameworks, where library code needs to create objects of types that applications using the framework may subclass. It is common in parallel class hierarchies to require objects from one hierarchy to be able to create appropriate objects from another.
Although the primary motivation behind the Factory Method pattern is to allow subclasses to choose which types of objects to create, there are other benefits to using factory methods, some of which do not depend on subclassing. Therefore, it is common to define "factory methods" that are not polymorphic in order to gain these other benefits.
Figure 8-19. UML class diagram for the Factory Method pattern
A Factory Method Example
The ultimate goal of this pattern is to encapsulate the creation of objects. For illustration purposes, you'll build a very ...
Get Programming .NET 3.5 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.