17.10. Creator
Problem Who should be responsible for creating a new instance of some class?The creation of objects is one of the most common activities in an object-oriented system. Consequently, it is useful to have a general principle for the assignment of creation responsibilities. Assigned well, the design can support low coupling, increased clarity, encapsulation, and reusability.Solution Assign class B the responsibility to create an instance of class A if one of these is true (the more the better):[10]
[10] Other creation patterns, such as Concrete Factory and Abstract Factory , are explored later.
- B "contains" or compositely aggregates A.
- B records A.
- B closely uses A.
- B has the initializing data for A that will be passed to A when it is created. Thus B is an Expert with respect to creating A.
B is a creator of A objects.If more than one option applies, usually prefer a class B which aggregates or contains class A.Example In the NextGen POS application, who should be responsible for creating a SalesLineItem instance? By Creator, we should look for a class that aggregates, contains, and so on, SalesLineItem instances. Consider the partial domain model in Figure 17.12.
Figure 17.12. Partial domain model.
Figure 17.13. Creating a SalesLineItem.
composition in considering the Creator pattern. A composite object is an excellent candidate to make its parts.composite aggregation p. 264 Sometimes you identify a creator by looking for the class that has the initializing data that will be passed in during creation. This is actually an example of the Expert pattern. Initializing data is passed in during creation via some kind of initialization method, such as a Java constructor that has parameters. For example, assume that a Payment instance, when created, needs to be initialized with the Sale total. Since Sale knows the total, Sale is a candidate creator of the Payment .Contraindications Often, creation requires significant complexity, such as using recycled instances for performance, conditionally creating an instance from one of a family of similar classes based upon some external property value, and so forth. In these cases, it is advisable to delegate creation to a helper class called a Concrete Factory or an Abstract Factory [GHJV95] rather than use the class suggested by Creator . Factories are discussed starting on p. 440.Benefits
- Low coupling is supported, which implies lower maintenance dependencies and higher opportunities for reuse. Coupling is probably not increased because the created class is likely already visible to the creator class, due to the existing associations that motivated its choice as creator.
Related Patterns or Principles
- Low Coupling
- Concrete Factory and Abstract Factory
- Whole-Part [BMRSS96] describes a pattern to define aggregate objects that support encapsulation of components.