Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.
Frameworks use abstract classes to define and maintain relationships between objects. A framework is often responsible for creating these objects as well.
Consider a framework for applications that can present multiple documents to the user. Two key abstractions in this framework are the classes Application and Document. Both classes are abstract, and clients have to subclass them to realize their application-specific implementations. To create a drawing application, for example, we define the classes DrawingApplication and DrawingDocument. The Application class is responsible for managing Documents and will create them as required—when the user selects Open or New from a menu, for example.
Because the particular Document subclass to instantiate is application-specific, the Application class can't predict the subclass of Document to instantiate—the Application class only knows when a new document should be created, not what kind of Document to create. This creates a dilemma: The framework must instantiate classes, but it only knows about abstract classes, which it cannot instantiate.
The Factory Method pattern offers a solution. It encapsulates the knowledge of which Document subclass to create and moves this knowledge out of the framework.
Application subclasses redefine an abstract CreateDocument operation on Application to return the appropriate Document subclass. Once an Application subclass is instantiated, it can then instantiate application-specific Documents without knowing their class. We call CreateDocument a factory method because it's responsible for "manufacturing" an object.
The next step is to translate the domain definitions into a number of Elisa components.
Based on the domain definitions a set of related components can be derived.
The first domain definition is a selection domain. It specifies a number of alternative domains. The implementation of selection domains is based on the concepts of categories. The following component implements the Application = MyApplication1 | MyApplication2.
The definitions in this component use patterns for dynamic type matching to select the definition rule which corresponds to the matching type.
The following component illustrates one of MyApplications:
The following component implements the Document = MyDocument1 | MyDocument2.
The following component is an example of a MyDocument component:
This page was last modified on 13-11-2012 16:07:54