Creator GRASP Pattern

Creator is the GRAS Patterns (General Responsibility Assignment Software Pattern)
Read about GRASP Patterns: GRASP Patterns Overview

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 or more of the following is true:
? B aggregates A objects.
? B contains A objects.
? B records instances of A objects.
? B closely uses A objects.
? B has the initializing data 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, prefer a class B which aggregates or contains class A.

Example 

Let's consider Point of Sale (POS) application: a Brief overview of POS application.
  • Application for a shop, restaurant, etc. that registers sales.
  • Each sale is of one or more items of one or more product types and happens at a certain date.
  • A product has a speci cation including a description, unitary price, and identifier.
  • The application also registers payments (say, in cash) associated with sales.
  • A payment is for a certain amount, equal or greater than the total of the sale.

Problem statement: who should be responsible for creating a SalesLineltem instance?

In the POS application, who should be responsible for creating a SalesLineltem instance? By Creator, we should look for a class that aggregates, contains, and so on, SalesLineltem instances.

Since a Sale contains (in fact, aggregates) many SalesLineltem objects, the Creator pattern suggests that Sale is a good candidate to have the responsibility of creating SalesLineltem instances.
This leads to a design of object interactions: Creating a SalesLineltem

Sample Code

class Sale {
List<SalesLineItem> salesLineItem
=
new ArrayList<SalesLineItem>();
//...
public void addLineItem(ProductSpecification prodSpec,int quantity) {
salesLineItem.add(
new SalesLineItem(prodSpec, quantity);
return salesLineItem;
}
}

Benefits

  • Low coupling (described next) 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 GRASP Patterns

Comments

Popular posts from this blog

Design Patterns used in Hibernate Framework

Value List Handler