You are on page 1of 50

Object Oriented Analysis and Design Design Patterns I

Matthew Dailey
Computer Science and Information Management Asian Institute of Technology

Matthew Dailey (CSIM-AIT)

Design Patterns I

1 / 50

Readings

Readings for these lecture notes: - Larman (2005), Applying UML and Patterns: An Introduction to Object-Oriented Analysis and Design and Iterative Development, 3rd edition, Chapter 17. Some material c Larman (2005).

Matthew Dailey (CSIM-AIT)

Design Patterns I

2 / 50

Outline

Introduction

Responsibility-Driven Design

Basic GRASP Patterns

Wrap-Up

Matthew Dailey (CSIM-AIT)

Design Patterns I

3 / 50

Introduction
Getting started with design modeling

Object-oriented design is not about UML. It is primarily about assigning responsibilities to objects. Design modeling normally begins on the rst elaboration iteration. The situation: A two-day requirements workshop has been completed. 10%20% of the requirements have been detailed. The large-scale architecture has been dened. We have use case text, system sequence diagrams, operation contracts, and a domain model. We organize a one-day modeling workshop.

Matthew Dailey (CSIM-AIT)

Design Patterns I

4 / 50

Introduction
Design guidelines

Some guidelines for the design process: For OOD we use the metaphor of responsibility-driven design. We attempt to determine how responsibilities should be divvied up between software objects. During design modeling, we focus on the dicult and/or creative parts of the design. We create models for communication and understanding, not for documentation.

Matthew Dailey (CSIM-AIT)

Design Patterns I

5 / 50

Introduction
Design outputs

Possible outputs of the design process: Interaction diagrams Class diagrams Package diagrams UI sketches Database design Report sketches

Matthew Dailey (CSIM-AIT)

Design Patterns I

6 / 50

Introduction
Artifact relationships
Sample UP Artifact Relationships Domain Model

We will begin realizing our use cases by assigning system operations from SSD analysis to software objects. We might derive the software classes from the domain model or create new classes. Then we will determine how those objects collaborate with other objects to implement the system operation including operation contract postconditions.
Matthew Dailey (CSIM-AIT)

Business Modeling

Sale date ...

1..*

Sales LineItem quantity ...

...

Use-Case Model Process Sale


Process Sale Cashier

use case names

1. Customer arrives ... 2. ... 3. Cashier enters item identifier. Use Case Text system events : System

Supplementary Specification

Requirements

Use Case Diagram ideas for the postconditions

functional requirements that must be realized by the objects Glossary

non-functional requirements domain rules

inspiration for names of some software domain objects

Operation: enterItem() Post-conditions: -... Operation Contracts

: Cashier

system operations

make NewSale() enterItem (id, quantity) item details, formats, validation

starting events to design for, and detailed postcondition to satisfy

System Sequence Diagrams

: Register enterItem (itemID, quantity)

Design Model

: ProductCatalog

: Sale

Design

d = getProductDescription(itemID) addLineItem( d, quantity ) Register ... makeNewSale() enterItem(...) ... ...

ProductCatalog

getProductDescription(...) ...

Larman (2005), Fig. 17.1


Design Patterns I 7 / 50

Outline

Introduction

Responsibility-Driven Design

Basic GRASP Patterns

Wrap-Up

Matthew Dailey (CSIM-AIT)

Design Patterns I

8 / 50

Responsibility-Driven Design
Introduction

Responsibility-driven design concerns object responsibilities, roles, and collaborations. There are two types of responsibilities: Doing responsibilities concern performing a task such as creating an object, performing a calculation, coordinating activities, and so on. Knowing responsibilities concern knowing about private data, related objects, data needed for calculations, and so on. We say that responsibilties are fullled by object methods.

Matthew Dailey (CSIM-AIT)

Design Patterns I

9 / 50

Responsibility-Driven Design
Example: Knowing responsibilities

Example of applying responsibility-driven design:

Knowing responsibilities will often be inspired by the domain model.


Given a domain object Sale having a time attribute, according to the principle of minimal representational gap, we would probably say that the Sale software object should be responsible for knowing its time.

Matthew Dailey (CSIM-AIT)

Design Patterns I

10 / 50

Responsibility-Driven Design
Collaborations

Collaborations mean the objects that cooperate to get work done. Collaboration example: a Sale object might invoke the getSubtotal method on multiple SaleLineItem objects to fulll the responsibility of calculating a total.

Matthew Dailey (CSIM-AIT)

Design Patterns I

11 / 50

Responsibility-Driven Design
GRASP

GRASP: General Responsibility Assignment Software Patterns or Principles. GRASP provides basic patterns or principles for assignment of responsibilities to objects. When drawing interaction diagrams, you are implicitly assigning responsibilities to particular objects. Use GRASP when drawing interaction diagrams and coding.

Matthew Dailey (CSIM-AIT)

Design Patterns I

12 / 50

Responsibility-Driven Design
Fundamental GRASP principles

5 fundamental GRASP principles/patterns:


Creator: who should be responsible for creating a specic object? Information Expert: who should be responsible for knowing about a particular object? Low Coupling: how strongly should elements be tied to others? Controller: who should be the rst to receive a message in the domain layer? High Cohesion: how should responsibilities be grouped within classes?

Matthew Dailey (CSIM-AIT)

Design Patterns I

13 / 50

Outline

Introduction

Responsibility-Driven Design

Basic GRASP Patterns

Wrap-Up

Matthew Dailey (CSIM-AIT)

Design Patterns I

14 / 50

Basic GRASP Patterns


Creator pattern

The Creator pattern: who should be responsible for creating instances of class A?
B creates A if: B contains A B records A B closely uses A B has the information needed to create A

Matthew Dailey (CSIM-AIT)

Design Patterns I

15 / 50

Basic GRASP Patterns


Creator principle

Example: in Monopoly, who should create the Square objects? First, consider the domain model:

Larman (2005), Fig. 17.3


Matthew Dailey (CSIM-AIT) Design Patterns I 16 / 50

Basic GRASP Patterns


Creator principle

The Board object contains Square objects, so it is a good candidate.

Larman (2005), Fig. 17.4

This gives us a clue that the relationship should be a composition:

Larman (2005), Fig. 17.5


Matthew Dailey (CSIM-AIT) Design Patterns I 17 / 50

Basic GRASP Patterns


Creator principle

Example: in the POS system, who should create the SalesLineItem objects? First, consider the domain model:
Sale time 1 Contains 1..* Sales LineItem quantity

Described-by

Product Description description price itemID

Larman (2005), Fig. 17.12

Matthew Dailey (CSIM-AIT)

Design Patterns I

18 / 50

Basic GRASP Patterns


Creator principle

We see that Sale contains SalesLineItem, so we give the responsibility to Sale in the dynamic model:
: Register : Sale

makeLineItem(quantity) create(quantity) : SalesLineItem

Larman (2005), Fig. 17.13

When object creation is suciently complex, involving recycling, polymorphism, and so on, it may be useful to separate the creation responsibility into a Factory helper class (GoF, Larman Ch. 26).
Matthew Dailey (CSIM-AIT) Design Patterns I 19 / 50

Basic GRASP Patterns


Information Expert principle

The Information Expert pattern: who should be responsible for knowing about instances of a class?
We assign knowing responsibilities to the class having the information needed to fulll the responsibility. When assigning knowing responsibilities, rst look in the design model for an appropriate class. If not found in the design model, look in the domain model.

Matthew Dailey (CSIM-AIT)

Design Patterns I

20 / 50

Basic GRASP Patterns


Information Expert principle

Example: in the Monopoly game, Board should have the responsibility to know about Square instances.

Larman (2005), Fig. 17.6

Matthew Dailey (CSIM-AIT)

Design Patterns I

21 / 50

Basic GRASP Patterns


Information Expert principle

Example: who should have the responsibility to know the total price for a sale? Domain model:
Sale time 1 Contains 1..* Sales LineItem quantity

Described-by

Product Description description price itemID

Larman (2005), Fig. 17.14

Matthew Dailey (CSIM-AIT)

Design Patterns I

22 / 50

Basic GRASP Patterns


Information Expert principle

We see that Sale already has the SalesLineItem objects needed to calculate the total:
t = getTotal :Sale time ... New method getTotal() Sale

Larman (2005), Fig. 17.15

Matthew Dailey (CSIM-AIT)

Design Patterns I

23 / 50

Basic GRASP Patterns


Information Expert principle

But to get the price of a SalesLineItem, we also need the ProductDescriptions price attribute. SalesLineItem has the needed information:
this notation will imply we are iterating over all elements of a collection time ... t = getTotal : Sale 1 *: st = getSubtotal lineItems[ i ] : SalesLineItem getTotal() Sale

SalesLineItem quantity New method getSubtotal()

Larman (2005), Fig. 17.16

Matthew Dailey (CSIM-AIT)

Design Patterns I

24 / 50

Basic GRASP Patterns


Information Expert principle

To fulll the responsibility to know its subtotal, the SalesLineItem needs to collaborate with ProductDescription:
Sale time ... t = getTotal : Sale 1 *: st = getSubtotal lineItems[ i ] : SalesLineItem getTotal()

1.1: p := getPrice()

SalesLineItem quantity

:Product Description

getSubtotal() Product Description description price itemID

New method

getPrice()

Larman (2005), Fig. 17.17

Matthew Dailey (CSIM-AIT)

Design Patterns I

25 / 50

Basic GRASP Patterns


Low Coupling principle

The Low Coupling principle: how to reduce the impact of change?


We assign responsibilities so that unnecessary coupling is low. Coupling means how strongly tied one element is to another. Coupling makes designs and code hard to understand and hard to modify. Use the low coupling principle to evaluate alternative designs.

Matthew Dailey (CSIM-AIT)

Design Patterns I

26 / 50

Basic GRASP Patterns


Low Coupling principle

Note that Information Expert reduces coupling. Consider an alternative design for the responsibility of knowing about Square objects:

Larman (2005), Fig. 17.7

Matthew Dailey (CSIM-AIT)

Design Patterns I

27 / 50

Basic GRASP Patterns


Low Coupling principle

Example: how to create a Payment object and associate it with a Sale? On the one hand, we might give Register the responsibility to create the Payment:
makePayment() : Register 1: create() p : Payment

2: addPayment(p)

:Sale

Larman (2005), Fig. 17.18

Matthew Dailey (CSIM-AIT)

Design Patterns I

28 / 50

Basic GRASP Patterns


Low Coupling principle

On the other hand, we might give Sale the responsibility to create the Payment:
makePayment() : Register 1: makePayment() :Sale

1.1. create()

:Payment

Larman (2005), Fig. 17.19

Which is better? It is unavoidable that Sale is coupled to Payment. But the rst design creates an unnecessary coupling of Sale to Register. All else being equal, we prefer the second.

Matthew Dailey (CSIM-AIT)

Design Patterns I

29 / 50

Basic GRASP Patterns


Low Coupling principle

Common kinds of coupling between TypeX and TypeY: TypeX has an attribute that refers to a TypeY instance or TypeY itself. A TypeX object calls on the services of a TypeY object. TypeX has a method referencing (via parameters, local variables, or return values) a TypeY instance. TypeX is a direct or indirect subclass of TypeY. TypeY is an interface, and TypeX implements that interface. Avoiding coupling is not always necessary. It is most important at points of instability. Therefore coupling to stable APIs like java.util is generally OK.

Matthew Dailey (CSIM-AIT)

Design Patterns I

30 / 50

Basic GRASP Patterns


Controller pattern

The Controller pattern: who should be responsible for receiving and coordinating a system operation?
We create controller objects to handle system operation messages. In most systems, actors will generate UI events. UI objects react to these elements then delegate to objects in the domain layer (or the intermediate application layer, if you have one). The rst object in the domain layer is called the controller for the system operation.

Matthew Dailey (CSIM-AIT)

Design Patterns I

31 / 50

Basic GRASP Patterns


Controller pattern

There are two main types of controller: A controller representing an entire system, root object, device, or subsystem is called a facade controller. Use a class name such as the name of the SuD. A controller responsible for one use case scenario is called a session controller. Use names such as <UseCaseName>Handler or <UseCaseName>Session. Note that the GRASP controller is not the same as the C in MVC!

Matthew Dailey (CSIM-AIT)

Design Patterns I

32 / 50

Basic GRASP Patterns


Controller pattern

Example: for the Monopoly game, there are few system operations:

Larman (2005), Fig. 17.8


Matthew Dailey (CSIM-AIT) Design Patterns I 33 / 50

Basic GRASP Patterns


Controller pattern

For playGame(), we need to identify the recipient of the system operation message:

Larman (2005), Fig. 17.9

Matthew Dailey (CSIM-AIT)

Design Patterns I

34 / 50

Basic GRASP Patterns


Controller pattern

In this case, since there are so few operations, we use the root object controller pattern:

Larman (2005), Fig. 17.10

Matthew Dailey (CSIM-AIT)

Design Patterns I

35 / 50

Basic GRASP Patterns


Controller pattern

Example: for the enterItem operation, we have a situation like this:

presses button

: Cashier actionPerformed( actionEvent )

UI Layer

:SaleJFrame system operation message enterItem(itemID, qty)?

Domain Layer

: ???

Which class of object should be responsible for receiving this system event message? It is sometimes called the controller or coordinator. It does not normally do the work, but delegates it to other objects. The controller is a kind of "facade" onto the domain layer from the interface layer.

Larman (2005), Fig. 17.21


Matthew Dailey (CSIM-AIT) Design Patterns I 36 / 50

Basic GRASP Patterns


Controller pattern

Some possible design alternatives:


enterItem(id, quantity) :Register

enterItem(id, quantity)

:ProcessSaleHandler

Larman (2005), Fig. 17.22

Matthew Dailey (CSIM-AIT)

Design Patterns I

37 / 50

Basic GRASP Patterns


Controller pattern

Combining with the other system operations, we can see the consequences of each design alternative:
System endSale() enterItem() makeNewSale() makePayment() makeNewReturn() enterReturnItem() ... ... endSale() enterItem() makeNewSale() makePayment() makeNewReturn() enterReturnItem() ... Register

system operations discovered during system behavior analysis

allocation of system operations during design, using one facade controller

System endSale() enterItem() makeNewSale() makePayment() enterReturnItem() makeNewReturn() ... ...

ProcessSale Handler ...

HandleReturns Handler

endSale() enterItem() makeNewSale() makePayment()

enterReturnItem() makeNewReturn() ...

allocation of system operations during design, using several use case controllers

Larman (2005), Fig. 17.23


Matthew Dailey (CSIM-AIT) Design Patterns I 38 / 50

Basic GRASP Patterns


Controller pattern

Some tips about controllers: The controller should be seen as a facade into the domain layer. Use the same controller for all system events involved in a use case. Controllers will often be stateful, maintaining information about the current progress of the use case. For purposes of cohesion, controllers should primarily delegate, (forward responsibility to other objects) wherever possible. In Java EE, controllers will oftentimes be stateful session Enterprise Java Beans. The controller may delegate directly to domain layer objects, or if it is in a separate application logic layer, it may make requests to other controllers in the pure domain layer.

Matthew Dailey (CSIM-AIT)

Design Patterns I

39 / 50

Basic GRASP Patterns


Controller pattern

Some controller antipatterns: A single controller with too many system events. No delegation. Duplication of information found elsewhere in the domain layer.

Matthew Dailey (CSIM-AIT)

Design Patterns I

40 / 50

Basic GRASP Patterns


Controller pattern

Dont allow direct manipulation of domain objects in the UI layer! Example (good design):

presses button

: Cashier actionPerformed( actionEvent )

UI Layer

:SaleJFrame

system operation message

1: enterItem(itemID, qty)

controller

Domain Layer

:Register

1.1: makeLineItem(itemID, qty)

:Sale

Larman (2005), Fig. 17.24


Matthew Dailey (CSIM-AIT) Design Patterns I 41 / 50

Basic GRASP Patterns


Controller pattern

Example (bad design):

presses button

Cashier actionPerformed( actionEvent ) It is undesirable for an interface layer object such as a window to get involved in deciding how to handle domain processes. Business logic is embedded in the presentation layer, which is not useful.

UI Layer

:SaleJFrame

Domain Layer

1: makeLineItem(itemID, qty)

:Sale

SaleJFrame should not send this message.

Larman (2005), Fig. 17.25


Matthew Dailey (CSIM-AIT) Design Patterns I 42 / 50

Basic GRASP Patterns


Controller pattern

In message processing systems, rather than a use case controller, we would most likely use the Command pattern in which we have one object for each possible type of incoming command (see Larman Ch. 37 for details).

Matthew Dailey (CSIM-AIT)

Design Patterns I

43 / 50

Basic GRASP Patterns


High Cohesion principle

The High Cohesion principle: how to keep objects focused, understandable, and manageable?
We assign responsibilities so that cohesion remains high, i.e., so that similar responsibilities are grouped into the same class. High cohesion is a principle used to evaluate competing designs.

Matthew Dailey (CSIM-AIT)

Design Patterns I

44 / 50

Basic GRASP Patterns


High Cohesion principle

Example of good and bad cohesion:

Larman (2005), Fig. 17.11

Matthew Dailey (CSIM-AIT)

Design Patterns I

45 / 50

Basic GRASP Patterns


High Cohesion principle

Example: for the POS system, when we design for the makePayment() system operation:
: Register : Sale

makePayment() create() p : Payment

addPayment( p )

Larman (2005), Fig. 17.26

We already saw that this creates an unnecessary coupling between Register and Payment. But it also reduces the cohesion of Register.
Matthew Dailey (CSIM-AIT) Design Patterns I 46 / 50

Basic GRASP Patterns


High Cohesion principle

By delegating Payment creation to Sale, we not only decrease coupling, but we also increase the cohesion of Register.
: Register : Sale

makePayment() makePayment() create() : Payment

Larman (2005), Fig. 17.27

Since Register has fewer responsibilities, it is more cohesive.


Matthew Dailey (CSIM-AIT) Design Patterns I 47 / 50

Basic GRASP Patterns


High Cohesion principle

Cohesion and coupling often go together: you will often see cases where increased coupling also causes low cohesion, and vice versa.

Matthew Dailey (CSIM-AIT)

Design Patterns I

48 / 50

Outline

Introduction

Responsibility-Driven Design

Basic GRASP Patterns

Wrap-Up

Matthew Dailey (CSIM-AIT)

Design Patterns I

49 / 50

Wrap-Up
Next step

Now that we know the basic principles of responsibility assignment, were ready to do detailed designs for some of our use cases. Later, well look at more advanced design patterns.

Matthew Dailey (CSIM-AIT)

Design Patterns I

50 / 50

You might also like