In Applying UML and Patterns, Craig Larman discusses nine GRASP (General Responsibility Assignment Software Patterns) patterns used as an aid for object design. I mentioned the GRASP Controller Pattern in a previous post and thought I would mention the GRASP Creator Pattern as well.
Problem: Who should be responsible for creating a new instance of some class?
Solution: Assign class B the responsibility to create an instance of class A if one of these is true (the more the better):
- 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 crated. Thus B is an Expert with respect to creating A.
In general, the class that contains (aggregates) A is typically the best class to create A because it will probably satisfy one or more of the options mentioned above.
You see this Creator Pattern all the time. A perfect example is adding a new DataRow to a DataTable. To get a new row, you ask the DataTable to create a new DataRow for you and then add the row to the table.
DataRow myRow = myTable.NewRow();
...
myTable.Rows.Add(myRow);
The DataTable object contains / aggregates DataRows and therefore is the logical class to create the DataRow.
By have the aggregate class create the child class, you also support the Information Expert, High Cohesion, and Low Coupling GRASP Patterns as well as the Creator Pattern. I will talk more about those GRASP Patterns in later posts.