26.4. Factory
This is also called Simple Factory or Concrete Factory. This pattern is not a GoF design pattern, but extremely widespread. It is also a simplification of the GoF Abstract Factory pattern (p. 597), and often described as a variation of Abstract Factory, although that's not strictly accurate. Nevertheless, because of its prevalence and association with GoF, it is presented now.The adapter raises a new problem in the design: In the prior Adapter pattern solution for external services with varying interfaces, who creates the adapters? And how to determine which class of adapter to create, such as TaxMaster-Adapter or GoodAsGoldTaxProAdapter ?If some domain object creates them, the responsibilities of the domain object are going beyond pure application logic (such as sales total calculations) and into other concerns related to connectivity with external software components.This point underscores another fundamental design principle (usually considered an architectural design principle): Design to maintain a separation of concerns . That is, modularize or separate distinct concerns into different areas, so that each has a cohesive purpose. Fundamentally, it is an application of the GRASP High Cohesion principle. For example, the domain layer of software objects emphasizes relatively pure application logic responsibilities, whereas a different group of objects is responsible for the concern of connectivity to external systems.Therefore, choosing a domain object (such as a Register ) to create the adapters does not support the goal of a separation of concerns, and lowers its cohesion.A common alternative in this case is to apply the Factory pattern, in which a Pure Fabrication "factory" object is defined to create objects.Factory objects have several advantages:
- Separate the responsibility of complex creation into cohesive helper objects.
- Hide potentially complex creation logic.
- Allow introduction of performance-enhancing memory management strategies, such as object caching or recycling.
Name: | Factory |
Problem: | Who should be responsible for creating objects when there are special considerations, such as complex creation logic, a desire to separate the creation responsibilities for better cohesion, and so forth? |
Solution: (advice) | Create a Pure Fabrication object called a Factory that handles the creation. |
Figure 26.5. The Factory pattern.
[View full size image]