Creator GRASP Pattern

1. Overview

Creator is a GRASP Pattern which helps to decide which class should be responsible for creating a new instance of a class. Object creation is an important process, and it is useful to have a principle in deciding who should create an instance of a class.
Read more about GRASP Patterns at GRASP Patterns Overview
Let's first start with what is a problem and then we will see how does Creator Pattern solve the problem.

2. Problem

Who should be responsible for creating a new instance of some class?

3. Solution

Creation of objects is one of the most common activities in an object-oriented system. Which class is responsible for creating objects is a fundamental property of the relationship between objects of particular classes.
In general, a class B should be responsible for creating instances of class A if one, or preferably more, of the following apply:
  • Instances of B contain or compositely aggregate instances of A
  • Instances of B record instances of A
  • Instances of B closely use instances of A
  • Instances of B have the initializing information for instances of A and pass it on creation

4. Creator GRASP Pattern Example

Let's consider Point of Sale (POS) application:  Here is a brief overview of the POS application.
  • POS 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 specification including a description, unitary price, an identifier.
  • The application also registers payments (say, in cash) associated with sales.
  • Payment is for a certain amount, equal to 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.
From the above class diagram, The Sale class contains (in fact, aggregates) many SalesLineltem objects, the Creator pattern suggests that Sale class is a good candidate to have the responsibility of creating SalesLineltem instances.

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;

5. 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 a creator.