Design Model - GRASP: Designing Objects With Responsibilities

Design Model - GRASP: Designing Objects
With Responsibilities
2
Objectives
 Define patterns
 Learn to apply five of the GRASP patterns
3
Patterns and Frameworks
 Pattern
 Provides a common solution to a common problem
in a context
 Analysis/Design Pattern
 Provides a solution to a narrowly scoped technical
problem
 Provides a fragment of a solution, or a piece of the
puzzle
 Framework
 Defines the general approach to solving the
problem
 Provides a skeletal solution, whose details may be
analysis/design patterns
4
What Is a Design Pattern?
 A design pattern provides a scheme for
refining the subsystems or components of
a software system, or the relationships
between them. It describes a commonlyrecurring
structure of communicating
components that solves a general design
problem within a particular context.
Erich Gamma et al. 1994. Design Patterns—Elements of
Reusable Object-Oriented Software
Pattern Name
Template
Parameters
5
Patterns
 A pattern
is a named problem/solution pair
that can be
applied in new context, with advice on how to apply it in
novel situations and discussion of its trade-offs
 Patterns
are general principles and idiomatic solutions
which are summarized from those experienced objectoriented
developers during work, and they are used to
guide others in the creation of software.
 Primitive examples from OOP:
 Model - View - Controller (MVC)
 Object - Attribute - Value (OAV)
 GRASP (Larman)
 Gang of Four (GoF; Gamma, et. al.)
6
Examples of Pattern Usage
Issue a request to an object without knowing anything about
the operation requested or the receiver of the request: for
example, the response to a menu item, an undo request, the
processing of a time-out
Command
(behavioral pattern)
When the state of an object changes, the dependent objects
are notified. The changed object is independent of the
observers.
Note: The MVC architectural pattern is an extension of the
Observer design pattern
Observer
(behavioral pattern)
Handle distributed objects in a way that is transparent to the
client objects (remote proxy)
Load a large graphical object or any entity object “costly” to
create/initialize only when needed (on demand) and in a
transparent way (virtual proxy)
Proxy
(structural pattern)
Create GUI objects (buttons, scrollbars, windows, etc.)
independent of the underlying OS: the application can be
easily ported to different environments
Abstract factory
(creational pattern)
Pattern Example
7
Detailing the Command Pattern
cmd.Process();
Application
Menu
+menu 1 MenuItem
- label : String
+ Clicked()
0..*
+items
Command
+ Process()
1
+cmd
8
Detailing the Command Pattern (continued)
cmd.Process();
AskUser();
DoOpen();
Application
Menu
+menu 1 MenuItem
- label : String
+ Clicked()
0..*
+items
Command
+ Process()
1
+cmd
OpenCommand
+ Process()
9
Detailing the Command Pattern (continued)
Initialization
The user selects the
Open… menu item
myapp ocmd :
OpenCommand
aNewItem :
MenuItem
2. AddItem("Open...",ocmd)
1. OpenCommand( )
3. MenuItem("Open...", ocmd)
A user
theMenuItem cmd :
Command
3. AskUser( )
4. DoOpen( )
1. Clicked( ) 2. Process( )
menu
10
Detailing the Command Pattern (continued)
Clicked():
cmd.Process();
AskUser();
DoOpen();
Application
Menu
+ AddItem(s : String, c : Command)
MenuItem
- label : String
+ Clicked()
+ MenuItem(s : String, c : Command)
Command
+ Process()
OpenCommand
+ Process()
+ OpenCommand()
- AskUser()
- DoOpen()
+menu 1
+items
0..*
+cmd
1
MenuItem():
cmd = c;
label = s;
11
Detailing the Command Pattern (continued)
app
Application CloseCommand
OpenCommand
gui
Menu MenuItem
com
Command
12
Representing Design Patterns in UML
 A design pattern is a parameterized
collaboration:
The parameters (stereotype <<role>>)
of the collaboration
ConcreteCommand
+ Process()
<<role>>
Client
<<role>>
Command
+ Process()
Invoker
<<role>>
Command
Client
Invoker
ConcreteCommand
13
Introduction to Object Design Process
 Object design
 After identifying your requirements and creating a
domain model
, then add methods
to the software
classes, and define the messaging
between the
objects to fulfill the requirements.
 The heart of developing an object-oriented
system
is to decide
 what methods belong where, and
 how the objects should interact is terribly
important and anything but trivial
14
What’s GRASP pattern
 GRASP - General Responsibility Assignment
Software Patterns
ftaesnoPSw  This approach to understanding and using design
principles is based on patterns of assigning
responsibilities
 The GRASP patterns are a learning aid to help
one understand essential object design, and apply
design reasoning in a methodical, rational,
explainable way
15
What’s responsibility
 Responsibility
A contract or obligation of a class
 Type of Responsibility
Doing:
 Doing something itself, such as creating an object or
doing a calculation
 Initiating action in other objects
 Controlling and coordinating activities in other objects.
Knowing:
 Knowing about private encapsulated data
 Knowing about related objects
 Knowing about things it can derive or calculate
16
Responsibilities, Methods and Interaction Diagrams
 Methods implements responsibilities
 Responsibilities are implemented using methods that either
act alone or collaborate with other methods and objects
 Responsibilities and methods are related and shown in
interaction diagram
: S ale
makePayment(cashTendered)
create(cashTendered) : Payment
implies Sale objects have a
responsibility to create Payments
17
Basic GRASP Patterns
 Expert
 Creator
 Controller
 High Cohesion
 Low Coupling
18
Pattern 1: Information Expert
 Solution
 Assign a responsibility to the information expert - the
class that has the information necessary to fulfill the
responsibility.
 Problem
 What is a general principle of assigning responsibilities
to objects?
 The most commonly used pattern
19
Case Study: Apply Expert Pattern in the design of POS
 What do we have to start the design
S a le
d a te
tim e
Sales
LineItem
quantity
Product
Specification
description
p rice
ite m ID
* Described-by
Contains
1 ..*
1
1
20
Continue
 Next, we need to design: how to get the grand total of a
sale
 Question:
 Who (which class) should handle this?
 Answer:
 the one who knows about all the
SalesLineltem
S a l e s L i n e l t e m
instances
of a sale and the sum of their subtotals
. So,
the Sale
instance is the answer
S a le
d a te
tim e
getTotal()
t := getTotal() :S a le
New method
21
Continue
 Q: What information is needed to determine the line item
subtotal?
 A: SalesLineltem.quantity
and ProductSpecification.price
are needed.
 The SalesLineltem
knows its quantity and its associated
ProductSpecification;
therefore, by Expert, SalesLineltem
should
determine the subtotal; it is the information expert
S a le
d a te
tim e
getTotal()
SalesLineItem
quantity
New method getSubtotal()
t := getTotal() : S a le 1 *: st := getSubtotal()
*
:SalesLineItem
:SalesLineItem
22
Continue
 In the last step, to fulfill the responsibility of getting its subtotal, a Sales-
Lineltem needs to know the product price.
 Q: Who should handle this?
 A: The ProductSpecificatioProductSpecification
is an information expert on answering its price;
therefore, a message must be sent to it asking for its price.
S a le
d a te
tim e
getTotal()
SalesLineItem
quantity
getSubtotal()
Product
Specification
description
p rice
ite m ID
New method getPrice()
:Product
Specification
1.1: p := getPrice()
t := getTotal() : S ale 1 *: st := getSubtotal()
*
:SalesLineItem
:SalesLineItem
23
Discuss Expert Pattern
 The main idea - give responsibility to individuals who have
the information necessary to fulfill a task
 Do It Myself
 The fulfillment of a responsibility often requires information
that is spread across different classes of objects. This
implies that there are many "partial“ information experts
who will collaborate in the task
Contraindications
 There are situations where a solution suggested by Expert
is undesirable, usually because of problems in coupling
and cohesion
Benefits
 Information encapsulation is maintained
 Class definitions are easier to understand and maintain
24
Pattern 2: Creator
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 g r e g a t e s
A objects
 B contains
c o n t a i n s
A objects
 B records
r e c o r d s
instances of A objects
 B closely
c l o s e l y
uses
u s e s
A objects
 B has
h a s
the initializing data
t h e i n i t i a l i z i n g d a t a
that will be passed to A when it is created
Problem
Who should be responsible for creating a new instance of
some class?
25
Case Study: Apply Create Pattern in POS
S a le
d a te
tim e
Sales
LineItem
quantity
Product
Specification
description
p rice
ite m ID
* Described-by
Contains
1 ..*
1
1
26
Continue
: Register : S a le
makeLineItem(quantity)
create(quantity) : SalesLineItem
Q: Who should be responsible for creating a SalesLineltem
instance?
A: Sale
S a l e
- since it aggregates
many SalesLineItem instances
It requires a makeLineItem method be defined in Sale
27
Discussion of Creator
 Creator pattern is used to find a creator that needs to be
connected to the created object in any event
 Creator suggests that the enclosing container or recorder
class is a good candidate for the responsibility of creating
the thing contained or recorded
 Sometimes a creator is found by looking for the class that
has the initializing data that will be passed in during
creation
For example, Sale  Payment
 Low coupling
(described next) is supported, which implies
lower maintenance dependencies and higher opportunities
for reuse
Contraindications
If creation requires significant complexity, We should
delegate creation to a helper class called a Factory
F a c t o r y
28
Pattern 3: Low Coupling
 Solution
 Assign a responsibility so that coupling remains low.
 Problem
 How to support low dependency, low change impact,
and increased reuse?
 Coupling
is a measure of how strongly one element is
connected to, has knowledge of, or relies on other
elements.
 A class with high (or strong) coupling relies on many other
classes will cause the following problems:
 Changes in related classes force local changes.
 Harder to understand in isolation.
 Harder to reuse because its use requires the additional
presence of the classes on which it is dependent
29
Case Study: Apply Low Coupling in POS
 Design 1: The Register class
couples the Payment class.
The Sale class couples the
payment class
 Design 2: The Sale class
couples the payment class
 Which one is better?
Purely from the point of view
of coupling, Design 2 is
preferable because overall
lower coupling is maintained.
: Register p : Payment
:S a le
makePayment() 1: create()
2: addPayment(p)
: Register :S a le
:Payment
makePayment() 1: makePayment()
1.1. create()
30
Discussion of Low Coupling
 Low Coupling
is a principle
to keep in mind during all
design decisions
; it is an underlying goal to continually
consider
 In object-oriented languages such as C++, Java, and C#,
common forms of coupling from TypeX
to TypeY
include:
 TypeX has an attribute (data member or instance variable)
that refers to a TypeY instance, or TypeY itself
 A TypeX object calls on services of a TypeY object
 TypeX has a method that references an instance of TypeY, or
TypeY itself, by any means. These typically include a
parameter or local variable of type
 TypeY, or the object returned from a message being an
instance of TypeY
 TypeX is a direct or indirect subclass of TypeY
 TypeY is an interface, and TypeX implements that interface
31
Continue
 Benefits
itesBfn
:
 not affected by changes in other components
 simple to understand in isolation
 convenient to reuse
32
Be careful of Inheritance
 A subclass is strongly coupled to its superclass.
Be careful since it is such a strong form of
coupling
 For example, suppose that objects need to be stored
persistently in a relational or object database. In this
case it is a relatively common design to create an
abstract superclass called PersistentObject from which
other classes derive
 Disadvantage
 It highly couples domain objects to a particular technical
service and mixes different architectural concerns
 Advantage
 Automatic inheritance of persistence behavior
33
Pattern 4: High Cohesion
 Solution
 Assign a responsibility so that cohesion remains high
 Problem
 How to keep complexity manageable?
 Cohesion
is a measure of how strongly related and
focused the responsibilities of an element (classes,
subsystems) are
 A class with low cohesion
does many unrelated things,
or does too much work
 They suffer from the following problems:
 hard to understand
 hard to reuse
 hard to maintain
 delicate; constantly effected by change
34
Benefits of High Cohesion
 Clarity and ease of comprehension of the design
is increased.
 Maintenance and enhancements are simplified.
 Low coupling is often supported.
 The fine grain of highly related functionality
supports increased reuse because a cohesive
class can be used for a very specific purpose.
35
Case Study: Apply High Cohesion in POS
 Low Cohesion
(Register has payment
responsibility, and
many other unrelated
responsibility)
 The second design
supports both high
cohesion and low
coupling, it is desirable.
: Register : S a le
makePayment()
create() : Payment
makePayment()
: Register : S a le
addPayment( p )
create() p : Payment
makePayment()
36
Discussion of High Cohesion
 In practice, consideration of cohesion should not isolate
from other responsibilities and other principles such as
Expert
and Low Coupling
 Like Low Coupling, High Cohesion is a principle to keep
in mind during all design decisions
 How we design a class with high cohesion?
 Assign a class with a relatively small number of methods, with
highly related functionality
, and does not do too much work. It
collaborates with other objects to share the effort if the task is large
 Contraindications
 Grouping responsibilities or code into one class or
component to simplify maintenance and development
 Distributed server objects
37
Pattern 5: Controller
 Solution
 Assign the responsibility for receiving or
handling a system event message
iltaesdghnm to a class
representing one of the following choices:
• Represents the overall system, device, or
subsystem (facade controller).
• Represents a use case scenario within which
the system event occurs
 Problem
 Who should be responsible for handling an input
system event?
38
Benefits of using controller
 A controller supports the reuse
reseu
of the logic and
pluggable interfaces
 It ensures that application logic is not handled in
the interface layer. Because an interface-ascontroller
design (it is bound to a particular
interface) reduces the opportunity to reuse logic
in future applications
 Reason about the state of the use case - It is
sometimes necessary to ensure that system
operations occur in a legal sequence
39
Case Study: Apply Controller in POS
 There are several system operations
(triggered by system events):
 endSale()
 enterItem()
 makeNewSale()
 makePayment()
40
Continue
 Design Question: Who should handle incoming system
events?
 Answer: By Controller pattern, we use a controller class to
handle all system events
actionPerformed( actionEvent )
:Register
: Cashier
:SaleJFrame
presses button
1: enterItem(itemID, qty)
1.1: makeLineItem(itemID, qty) :S a le
Interface Layer
Domain Layer
system event message
controller
41
Continue – Type of Controllers
 The controller is a kind of
facade into the domain layer
from the interface layer
 Two Types of Controller
 Facade Controller -
Represents the overall
"system," device, or
subsystem Register,
R e g i s t e r ,
POSSystem
P O S y s t e m
 Use-Case Controller -
Represents a receiver or
handler of all system
events of a use case
scenario
ProcessSaleHandler
P r o c e s S a l e H a n d l e r
enterItem(id, quantity) :Register
enterItem(id, quantity) :ProcessSaleHandler
42
Choice of Controller Type
 Facade controllers
are suitable when
 there are not "too many" system events
, or
 it is not possible for the user interface (UI) to
redirect system event messages to alternating
controllers
, such as in a message processing
system
 Choose Use-Case controller
if a facade controller
leads to designs with low cohesion or high coupling
,
typically when the facade controller has excessive
responsibilities
.
 A use-case controller is a good choice when there
are many system events across different processes
43
Avoid Bloated Controllers
 Poorly designed, a controller class will have low cohesion - unfocused
and handling too many areas of responsibility
 this is called a bloated controller
 Signs of bloating include:
 There is only a single
s i n g l e
controller
(facade controller) class receiving
all system events in the system, and there are many of them
 The controller itself performs many of the tasks to fulfill the
system event
. This usually involves a violation of Information
Expert and High Cohesion.
 A controller has many attributes, and maintains significant
information about the system or domain,
which should have
been distributed to other objects, or duplicates information found
elsewhere
 In this case, we can
 Add more controllers (use-case controllers)
 Design the controller so that it delegates the fulfillment of each
system operation responsibility on to other objects
44
Interface Layer Should not Handle System Events
 Assigning the
responsibility for system
operations to objects in
the application or
domain layer—using the
Controller pattern rather
than the interface layer
supports increased
reuse
reseu
potential
Cashier
:SaleJFrame
actionPerformed( actionEvent )
:S a le
1: makeLineItem(itemID, qty)
Interface Layer
Domain Layer
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.
SaleJFrame should not
send this message.
presses button
45
Controller Class(es) in POS
Register
...
endSale()
enterItem()
makeNewSale()
makePayment()
makeNewReturn()
enterReturnItem()
. . .
S yste m
endSale()
enterItem()
makeNewSale()
makePayment()
makeNewReturn()
enterReturnItem()
. . .
system operations
discovered during system
behavior analysis
allocation of system
operations during design,
using one facade controller
ProcessSale
Handler
...
endSale()
enterItem()
makeNewSale()
makePayment()
S yste m
endSale()
enterItem()
makeNewSale()
makePayment()
enterReturnItem()
makeNewReturn()
. . .
allocation of system
operations during design,
using several use case
controllers
HandleReturns
Handler
...
enterReturnItem()
makeNewReturn()
. . .
46
Middle-Term Exam – Produce Analysis Model for
the Payroll Application
47
Mid-term Exam: Analysis Model
 Given the following:
 Use-Case Model, especially the usecase
flows of events
• Payroll Requirements, Use-Case
Model section
 Key abstractions/classes
• Architectural Analysis section
 The Supplementary Specification
• Payroll Requirements,
Supplementary Specification
section
48
Mid-term Exam: Analysis Model
 Identify the following for a particular use
case:
 The analysis classes, along with their:
• Brief descriptions
• Stereotypes
• Responsibilities
 Produce the following for all the use cases:
• The collaborations needed to implement
the use case
 Use-Case Realization - Interaction
diagram for the use-case flows of
events
49
Mid-term Exam: Analysis Model
• Analysis class attributes and
relationships
 VOPC class diagram, containing the
analysis classes, their stereotypes,
responsibilities, attributes, and
relationships
 Due Date: 14th May 8:00 am
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值