100 likes | 128 Views
TK2023 Object-Oriented Software Engineering. CHAPTER 13a GRASP Patterns: Creator. GRASP PATTERNS: CREATOR. 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:
E N D
TK2023 Object-Oriented Software Engineering CHAPTER 13a GRASP Patterns: Creator
GRASP PATTERNS: CREATOR 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: • 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. B is said to be a creator of A objects.
EXAMPLE OF APPLICATION • In the POS application, when the Cashier enters a new item, a line item needs to be created and associated with the current sale. • Referring to the domain model, Sale time 1 Contains * 1 .. Product Sales Description * 1 LineItem Described - by description quantity price itemID
We have a design problem… who should be responsible for creating a SalesLineItem instance? • The Creator pattern suggests that Sale is a good candidate to be assigned that responsibility as a Sale contains many SalesLineItem objects (according to our domain model).
: Register : Sale makeLineItem() SalesLineItem() : SalesLineItem {new} • One way to realize this is to define a method in the Sale class which will carry out that responsibility. Let’s call this method makeLineItem() (for now, we’ll ignore its parameters).
DISCUSSION • A very common task in object design is assigning responsibilities related to the creation of objects. The Creator pattern provides guidance for doing this. • The basic intent of the Creator pattern is to find a creator that needs to be connected to the created object in any event. Choosing that object as the creator supports low coupling.
Register SalesLineItem Sale : Register : Sale makeLineItem() SalesLineItem() SalesLineItem {new} :
Register SalesLineItem Sale : Register : Sale • Consider the following realization: SalesLineItem() s1 : SalesLineItem {new} addLineItem(s1) Coupling is increased!
Creator suggests that the enclosing container or recorder class is a good candidate for the responsibility of creating the thing contained or recorded. • Remember that the Creator pattern only provides a guideline. Use your judgement in deciding whether or not to apply the pattern.
: Register : Sale makePayment() Payment(total) : Payment {new} • Sometimes a creator can be identified by looking for the class that has the initializing data that will be passed in during creation. • For example, supposing a Payment object needs to be initialized to the total of the current Sale. Since Sale knows the total, it is a candidate creator of the Payment.