Title: Design Model - GRASP: Designing Objects With Responsibilities
1Design Model - GRASP Designing ObjectsWith
Responsibilities
2Objectives
- Define patterns
- Learn to apply five of the GRASP patterns
3Patterns 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
4What 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 commonly-recurring structure of
communicating components that solves a general
design problem within a particular context. - Erich Gamma et al. 1994. Design PatternsElements
of Reusable Object-Oriented Software
5Patterns
- 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 object-oriented 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.)
6Examples of Pattern Usage
Pattern Example
Command (behavioral pattern) 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
Abstract factory (creational pattern) Create GUI objects (buttons, scrollbars, windows, etc.) independent of the underlying OS the application can be easily ported to different environments
Proxy (structural 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)
Observer (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
7Detailing the Command Pattern
menu
1
1
MenuItem
1
1
Command
0..
0..
Menu
- label String
Process()
items
cmd
Clicked()
cmd.Process()
8Detailing the Command Pattern (continued)
menu
1
1
MenuItem
0..
0..
Menu
- label String
items
Clicked()
cmd.Process()
9Detailing the Command Pattern (continued)
1. OpenCommand( )
Initialization
2. AddItem("Open...",ocmd)
3. MenuItem("Open...", ocmd)
3. AskUser( )
4. DoOpen( )
The user selects the Open menu item
1. Clicked( )
2. Process( )
theMenuItem
cmd
Command
A user
10Detailing the Command Pattern (continued)
menu
1
1
MenuItem
Menu
0..
0..
- label String
items
AddItem(s String, c Command)
Clicked()
MenuItem(s String, c Command)
cmd
1
Command
Process()
11Detailing the Command Pattern (continued)
gui
Menu
MenuItem
com
Command
12Representing Design Patterns in UML
- A design pattern is a parameterized
collaboration
The parameters (stereotype ltltrolegtgt) of the
collaboration
ltltrolegtgt
Client
ltltrolegtgt
ConcreteCommand
Process()
ltltrolegtgt
Invoker
Command
Process()
13Introduction 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
14Whats GRASP pattern
- GRASP - General Responsibility Assignment
Software Patterns - 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
15Whats 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
16Responsibilities, 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
17Basic GRASP Patterns
- Expert
- Creator
- Controller
- High Cohesion
- Low Coupling
18Pattern 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
19Case Study Apply Expert Pattern in the design of
POS
- What do we have to start the design
20Continue
- 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
instances of a sale and the sum of their
subtotals. So, the Sale instance is the answer
21Continue
- 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
22Continue
- 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 ProductSpecification is an information
expert on answering its price therefore, a
message must be sent to it asking for its price.
23Discuss 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
24Pattern 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 objects
- B contains A objects
- B records instances of A objects
- B closely uses A objects
- B has the initializing data that will be passed
to A when it is created - Problem
- Who should be responsible for creating a new
instance of some class?
25Case Study Apply Create Pattern in POS
26Continue
Q Who should be responsible for creating a
SalesLineltem instance? A Sale - since it
aggregates many SalesLineItem instances It
requires a makeLineItem method be defined in Sale
27Discussion 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
28Pattern 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
29Case 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.
30Discussion 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
31Continue
- Benefits
- not affected by changes in other components
- simple to understand in isolation
- convenient to reuse
32Be 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
33Pattern 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
34Benefits 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.
35Case 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.
36Discussion 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
37Pattern 5 Controller
- Solution
- Assign the responsibility for receiving or
handling a system event message 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?
38Benefits of using controller
- A controller supports the reuse of the logic and
pluggable interfaces - It ensures that application logic is not handled
in the interface layer. Because an
interface-as-controller 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
39Case Study Apply Controller in POS
- There are several system operations (triggered by
system events) - endSale()
- enterItem()
- makeNewSale()
- makePayment()
40Continue
- Design Question Who should handle incoming
system events? - Answer By Controller pattern, we use a
controller class to handle all system events
41Continue 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,
POSSystem - Use-Case Controller - Represents a receiver or
handler of all system events of a use case
scenario ProcessSaleHandler
42Choice 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
43Avoid 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 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
44Interface Layer Should not Handle System Events
- Assigning the responsibility for system
operations to objects in the application or
domain layerusing the Controller pattern rather
than the interface layer supports increased reuse
potential
45Controller Class(es) in POS
46Middle-Term Exam Produce Analysis Model for the
Payroll Application
47Mid-term Exam Analysis Model
- Given the following
- Use-Case Model, especially the use-case flows of
events - Payroll Requirements, Use-Case Model section
- Key abstractions/classes
- Architectural Analysis section
- The Supplementary Specification
- Payroll Requirements, Supplementary Specification
section
48Mid-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
49Mid-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 800 am