0% found this document useful (0 votes)
14 views

OOSD Module 5

Uploaded by

Nivedita Tiwari
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

OOSD Module 5

Uploaded by

Nivedita Tiwari
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 75

ASET

Object-Oriented Systems Design

B.Tech Computer Science & Engineering


VII Semester (2017-21)

CSE431
Dr. Bramah Hazela
ASET

Module V

GRASP & UML


Module V : Design pattern- GRASP and UML
ASET

Descriptors/Topics
• GRASP: Designing objects with
responsibilities ,Creator , Information expert
• Low Coupling –Controller – High Cohesion,
Designing for visibility
• Applying GoF design patterns – adapter,
singleton, factory and observer patterns.
• UML state diagrams and modeling – Operation
contracts- Mapping design to code
• UML deployment and component diagrams
3
ASET

*GRASP: Designing
Objects with
Responsibilities

* Source : Applying UML and Patterns


Craig Larman
Chapter 17
Learning Objectives ASET

• Learn about design patterns


• Learn how to apply five GRASP patterns

• You’ve learned about static class diagrams


and dynamic interaction diagrams
• UML is just notation; now you need to learn
how to make effective use of the notation
• UML modeling is an art, guided by principles
Design patterns in architecture ASET

• A pattern is a recurring solution to a standard problem,


in a context.
• Christopher Alexander, professor of architecture…
– Why is what a prof of architecture
says relevant to software?
– “A pattern describes a problem
which occurs over and over again
in our environment, and then
describes the core of the solution
to that problem, in such a way that
you can use this solution a million
times over, without ever doing it
the same way twice.”
Design and dress patterns ASET

• Jim Coplein, a software engineer:


“I like to relate this definition to dress patterns …
I could tell you how to
make a dress by specifying
the route of a scissors
through a piece of cloth
in terms of angles and
lengths of cut. Or, I could
give you a pattern.
Reading the specification,
you would have no idea
what was being built or if you had built the right thing when
you were finished. The pattern foreshadows the product:
it is the rule for making the thing, but it is also,
in many respects, the thing itself.”
Patterns in engineering
ASET

• How do other engineers find and use patterns?


– Mature engineering disciplines have handbooks
describing successful solutions to known problems
– Automobile designers don't design cars from scratch
using the laws of physics
– Instead, they reuse standard designs with successful
track records, learning from experience
– Should software engineers make use of patterns?
Why?
– “Be sure that you make everything according to the pattern
I have shown you here on the mountain.” Exodus 25:40.
• Developing software from scratch is also expensive
– Patterns support reuse of software architecture design
Definitions and names ASET

• Alexander: “A pattern is a recurring solution


to a standard problem, in a context.”
• Larman: “In OO design, a pattern is a named
description of a problem and solution that can be
applied in new contexts; ideally,
a pattern advises us on how to apply the solution
in varying circumstances and considers
the forces and trade-offs.”
• How is Larman’s definition similar to Alexander’s?
• How are these definitions significantly different?
Naming Patterns—important!
ASET

• Patterns have suggestive names:


– Arched Columns Pattern, Easy Toddler Dress Pattern,
etc.
• Why is naming a pattern or principle helpful?
– It supports chunking and incorporating that concept
into our understanding and memory
– It facilitates communication

Star and Plume Quilt


GRASP ASET

• Name chosen to suggest the importance of


grasping fundamental principles to successfully
design object-oriented software
• Acronym for General Responsibility
Assignment Software Patterns
• Describe fundamental principles of
object design and responsibility
• Expressed as patterns
Five GRASP patterns: ASET

• Creator
• Information Expert
• Low Coupling
• Controller
• High Cohesion
Creator pattern ASET

Name: Creator
Problem: Who creates an instance of A?
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 aggregates A (in a collection)
• B records A
• B closely uses A
• B has the initializing data for A
Who creates the Squares?
ASET

Figure 17.3, page 283


How does Create pattern lead to
ASET
this partial Sequence diagram?

Figure 17.4, page 283


How does Create pattern develop
this Design Class Diagram (DCD)? ASET

Figure 17.5 , page 283

Board has a composite aggregation relationship with Square


• I.e., Board contains a collection of Squares
Discussion of Creator pattern
ASET

• Responsibilities for object creation are common


• Connect an object to its creator when:
– Aggregator aggregates Part
– Container contains Content
– Recorder records
– Initializing data passed in during creation
Contraindications or caveats ASET

• Creation may require significant complexity:


– recycling instances for performance reasons
– conditionally creating instances from a family
of similar classes
• In these instances, other patterns are
available…
– We’ll learn about Factory and other patterns later…
Information Expert
ASET
pattern or principle
Name: Information Expert
Problem: How to assign responsibilities to objects?
Solution: Assign responsibility to the class that has
the information needed to fulfill it?
• E.g., Board information needed to get a Square
Benefits and Contraindications ASET

• Facilitates information encapsulation: why?


– Classes use their own info to fulfill tasks
• Encourages cohesive, lightweight class definitions

But:
• Information expert may contradict patterns of
Low Coupling and High Cohesion
• Remember separation of concerns principle
for large sub-systems
• I.e., keep “business” or application logic
in one place, user interface in other place,
database access in another place, etc.
Low Coupling Pattern ASET

• Name: Low Coupling


• Problem: How to reduce the impact of
change and encourage reuse?
• Solution: Assign a responsibility so that
coupling (linking classes) remains low.
Why does the following design
violate Low Coupling? ASET

Why is a better idea to leave


getSquare responsibility in Board?
Benefits & Contraindications ASET

• Understandability: Classes are easier


to understand in isolation
• Maintainability: Classes aren’t affected by
changes in other components
• Reusability: easier to grab hold of classes
But:
• Don’t sweat coupling to stable classes (in
libraries or pervasive, well-tested classes)
Controller pattern ASET

• Name: Controller
(see Model-View-Controller architecture)
• Problem: Who should be responsible for UI
events?
• Solution: Assign responsibility for receiving or
handling a system event in one of two ways:
– Represent the overall system (façade pattern)
– Represent a use case scenario within which the
system event occurs (a session controller)
Who is the controller of playGame operation?
ASET

Figure 17.9, p. 288

What class represents the overall system


or relevant use case scenario?
High Cohesion pattern ASET

• Cohesion measures how strongly related and


focused are the responsibilities of an element
• Name: High Cohesion
• Problem: How to keep classes focused and
manageable?
• Solution: Assign responsibility so that cohesion
remains high.
How does the design on right promote high
cohesion? ASET

Delegate responsibility & coordinate work


Benefits & ContraindicationsASET

• Understandability, maintainability
• Complements Low Coupling
But:
• Avoid grouping of responsibilities or code into one
class or component to simplify maintenance by
one person. Why?
• Sometimes desirable to create less cohesive server
objects that provide an interface for many
operations, due to performance needs associated
with remote objects and remote communication
Summary ASET

• Skillful assignment of responsibilities is


extremely important in object-oriented design
(CRC cards are one technique)
• Patterns are named problem/solution pairs that
codify good advice and principles related to
assignment of responsibilities
• GRASP identifies five patterns or principles:
– Creator, Information Expert, Controller,
Low Coupling and High Cohesion
Design patterns ASET

• A design pattern is a way of reusing


abstract knowledge about a problem and
its solution
• A pattern is a description of the problem
and the essence of its solution
• It should be sufficiently abstract to be
reused in different settings
• Patterns often rely on object
characteristics such as inheritance and
polymorphism
Pattern elements ASET

• Name
– A meaningful pattern identifier
• Problem description
• Solution description
– Not a concrete design but a template for a
design solution that can be instantiated in
different ways
• Consequences
– The results and trade-offs of applying the
pattern
The Observer pattern ASET

• Name
– Observer
• Description
– Separates the display of object state from the object
itself
• Problem description
– Used when multiple displays of state are needed
• Solution description
– See slide with UML description
• Consequences
– Optimisations to enhance display performance are
impractical
The Observer pattern ASET

Subject Observer

Attach (Observer) Update ()


Detach (Observer)
Notify () for all o in observers
o -> Update ()

ConcreteSubject ConcreteObserver

GetState () Update () observerState =


return subjectState subject -> GetState ()
subjectState observerState
Why learn Design Patterns
ASET

• They make it easier to reuse successful designs


and architectures
• They can make documentation and maintenance of
the systems easier
• Design Patterns help a designer design “right”
faster
• They provide a vocabulary that can be used
amongst software developers.
• Enable us to discuss low-level implementation in a
high-level, abstract manner.
• Help in extendibility and avoiding solution redesign
34
Describing a Design Pattern ASET

• Pattern Name & Classification – Conveys the


essence of the pattern concisely
• Intent – What design issue the pattern addresses
• Also Known As – Other well known names for this
pattern
• Motivation – A scenario illustrating a design problem
and how its being solved by the pattern
• Applicability – Known situations where the pattern
can be applied
• Structure – OMT (Object Modeling ) based graphic
representation of the classes in the pattern
• Participants – Classes and objects in the pattern
with their responsibilities 35
Describing a Design Pattern Cont’d
ASET

• Collaborations – How the participants collaborate


to carry out their responsibilities
• Consequences – What are the results and
tradeoffs of using the pattern
• Implementation – Hints on implementation of the
pattern like language dependency
• Sample Code – Sample code
• Known Uses – Examples
• Related Patterns – Other patterns closely related
with the pattern under consideration

36
Not a Design Pattern ASET

• Linked Lists
• Hash Tables
• Domain Specific designs for entire
application or subsystem
• A code solution ready for copy-and-
paste
• Programming language features
• The same every time you see them 37
Design Patterns Classification ASET

• According to the GOF, the design


patterns can be classified in two ways
– According to the PURPOSE
– According to the SCOPE
• PURPOSE of Design Patterns reflect
what actually they do
• SCOPE of Design Patterns reflect
whether they apply primarily to
38
Classes or Objects.
Purpose based Design Patterns Classification
ASET

• Creational – Concerned with the


purpose of object creation or class
instantiation

• Structural – Deal with composition of


classes and objects

• Behavioral – Characterize the ways in


which classes and objects interact and 39
distribute resposibility.
Scope Based Design Patterns Classification
ASET

• Class Patterns deals with the relationships


amongst the classes and their subclasses
• These relationships are established through
INHERITANCE, so they are static – fixed at
compile time
• Object Patterns deals with object relationships
which can be changed at runtime or are dynamic
• Note that most patterns are object patterns

40
Design Patterns Classification
ASET

Purpose

Creational Structural Behavioral

Scope Class Factory Method Adapter(Class) Interpreter


Template Method

Object Abstract Factory Adapter(Object) Chain of Responsibility


Builder Bridge Command
Prototype Composite Iterator
Singleton Decorator Mediator
Façade Memento
Flyweight Observer
Proxy State
Strategy
Visitor

41
How Design Patterns Solve Design Problems
ASET

• Finding appropriate objects


– The hard part about OOD is decomposing a system into
objects
– They help to introduce an abstraction for treating objects
uniformly that doesn’t have a physical counterpart
– They help to identify less obvious abstractions and objects
that can capture them
– These objects are seldom identified in a design earlier and
are discovered while making the design reusable and more
flexible
• Determining the object Granularity
– They help in specifying how to represent complete
subsystems as objects
– They help you in decomposing objects into smaller objects

42
How Design Patterns Solve Design Problems
ASET

• Specifying Object Interfaces


– Help you in defining interfaces and the kinds of
data that get sent across them
– Might also tell what NOT to put into an interface
– Also specify relationships across interfaces
• Designing for Change
– Help you to avoid dependence on specific
operations
– Help you to avoid dependence on hardware and
software platforms
– Help to avoid algorithmic dependencies
43
Patterns and Algorithms ASET

• Algorithms and data structures


generally solve more fine-grained
computational problems like sorting
and searching.
• Patterns are typically concerned with
broader architectural issues that have
larger-scale effects.

44
Patterns and Frameworks ASET

• A software framework is a set of cooperating


classes that make up a reusable design for a
specific class of software [Deu89,JF88]
• A framework will dictate overall structure,
partitioning of classes and objects, how the classes
or objects collaborate
• A framework is usually not a complete application:
it often lacks the necessary application-specific
functionality.
• Examples
– Framework for building compiler for different languages
and machines.
– For building financial modeling applications
45
Patterns and Frameworks ASET

• Design patterns may be employed both in the design and the


documentation of a framework. A single framework typically
encompasses several design patterns. A framework can be
viewed as the implementation of a system of design patterns.
• Frameworks and design patterns are distinct: a framework is
executable software, design patterns represent knowledge
and experience about software. Frameworks are of a physical
nature, patterns are of a logical nature: frameworks are the
physical realization of one or more software pattern solutions;
patterns are the instructions for how to implement those
solutions.
• Major differences:
– Design patterns are more abstract than frameworks.
– Design patterns are smaller architectural elements than
frameworks.
– Design patterns are less specialized than frameworks.
46
An Example Case ASET

• Goals
– Learn how to exploit and gain experience
of others
– Examine the benefits of design pattern
– Learn one specific pattern: Strategy
pattern

47
Simple Simulation of Duck behavior
ASET

Duck

quack()
swim()
display()
// other duck methods

MallardDuck RedheadDuck

display() display() Other duck


// looks like mallard // looks like redhead types

48
Simple Simulation of Duck behavior
ASET

• All ducks Quack and Swim the super


class DUCK takes care of the
implementation code. But
• Each duck subtype is responsible for
implementing its own Display method
as each duck looks different
• In the super class the Display method
is abstract.
49
WHAT IF WE WANT TO SIMULATE FLYING
ASET
DUCKS?

Duck

quack()
swim()
display()
fly()
// other duck methods

MallardDuck RedheadDuck

display() display() Other duck


// looks like mallard // looks like redhead types

50
Tradeoffs in use of inheritance and maintenance
ASET

Duck
One could override the
quack() fly method to the appropriate
swim() thing – just as the quack
display()
method below.
fly()
// other duck methods

MallardDuck
RedheadDuck
RubberDuck
display()
// looks like mallard display()
// looks like redhead quack()
//overridden to squeak
display()
// looks like rubberduck
fly()
// override to do nothing 51
Example complicated: add a wooden decoy ducks to the mix
ASET

DecoyDuck
Inheritance is not always the right
answer. Every new class that inherits
quack(){ unwanted behavior needs to be
// override to do nothing overridden.
}
display()
How about using interfaces instead?
// display decoy duck
fly (){
//override to do nothing
}

52
Using Interfaces in Our Example
ASET

• We can take Fly() out of the superclasses


• We make an interface iFlyable containing
the Fly() method. That way the ducks
supposed to fly can implement that
interface and have a Fly() method
• Same solution can be implemented for
Quack(), we can make interface
iQuackable containing the Quack()
method
53
Duck simulation recast using interfaces
ASET

Interfaces
Flyable Quackable Duck

fly() quack() swim()


display()
// other duck methods

MallardDuck RedheadDuck RubberDuck DecoyDuck

display() display() display() display()


fly() fly() quack()
quack() quack()

54
Pros & Cons ASET

• Not all inherited methods make sense for all


subclasses – hence inheritance is not the right
answer
• But by defining interfaces, every class that needs
to support that interface needs to implement that
functionality… destroys code reuse and creates a
maintenance issue.
• So if you want to change the behavior defined by
interfaces, every class that implements that
behavior may potentially be impacted
AND
• Change is constant in Software Development
• Overtime an application must change and grow or
it will die…
55
Design Principles to the Rescue
ASET

• Identify the aspects of your application that


vary and separate them from what stays the
same.
OR
Take the parts that vary and encapsulate
them, so that later you can alter or extend
the parts that vary without affecting those
that don’t.
 Program to an interface, not to an implementation (Discussed
Later)
56
Change in Duck Classes According to the Design Principle
ASET

• As far as we can tell other than the problems with


Fly() and Quack() the Duck Class is fine.
• Now to separate “the parts that change from those
which remain the same”, we can create two sets of
classes apart from the Duck Class.
• One set can represent the Quacking behaviors e.g.
a class implements quacking, another implements
squeaking etc.
• Similar is the case with Flying behaviors

57
ASET

58
Design Principle ASET

• Program to an interface, not to an implementation


• We will use interfaces to represent each behavior
• Each Implementation of behavior will implement these
interfaces
• So the duck classes won’t implement these interfaces
instead the set of classes for behavior would implement
them.
• With our new design the duck classes would USE a
behavior represented by an interface. OR
• The actual implementation won’t be locked in the duck
classes.
59
Implementing duck behaviors - revisited
ASET

<<interface>> <<interface>>
FlyBehavior QuackBehavior

fly() quack()

Quack MuteQuack

quack(){ quack(){
// implements duck // do nothing –
FlyWithWings FlyNoWay quacking Can’t quack
} }
fly(){ fly(){
// implements duck // do nothing – Squeak
flying Can’t fly
} } quack(){
// implements duck
Key now is that Duck class will delegate its squeak
flying and quacking behavior instead of } 60
implementing these itself
In the Duck simulation context…
ASET

Duck

FlyBehavior: flyBehavior Duck


QuackBehavior: quackBehavior
Behaviors
performQuack()
swim()
display()
performFly()
//other duck-like methods

61
Duck simulation recast using the new
approach ASET

<<interface>>
FlyBehavior
Duck
fly()
FlyBehavior: flyBehavior
QuackBehavior: quackBehavior FlyWithWings FlyNoWay
fly() fly()
performQuack() // implements duck // do nothing –
performFly() flying Can’t fly
setFlyBehavior()
<<interface>>
setQuackBehavior()
QuackBehavior
swim()
display() quack()

Quack Squeak
quack() quack()
MallardDuck RedHeadDuck RubberDuck DecoyDuck // implements duck // implements
quacking squeak
display() display() display() display()
Mutequack
quack()
// do nothing

62
Design Principle ASET

• Favor composition over inheritance


• HAS-A can be better than IS-A
• Composition lets you encapsulate a
family of algorithms into their own set
of classes.
• Allows changing behavior at run time

63
The strategy pattern ASET

The Strategy Pattern defines a family of algorithms,


Encapsulates each one, and makes them
interchangeable. Strategy lets the algorithm vary
independently from clients that use it.

64
ASET

UML
State Machine Diagrams
State Machine Diagrams ASET

• A state machine diagram models the • The door can be in one of three states:
behavior of a single object, specifying "Opened", "Closed" or "Locked". It can
the sequence of events that an object respond to the events Open, Close,
goes through during its lifetime in Lock and Unlock. Notice that not all
response to events. As an example, events are valid in all states; for
the following state machine diagram example, if a door is opened, you
shows the states that a door goes cannot lock it until you close it. Also
through during its lifetime. notice that a state transition can have
a guard condition attached: if the door
is Opened, it can only respond to the
Close event if the condition
• doorWay->isEmpty is fulfilled. The
syntax and conventions used in state
machine diagrams will be discussed in
full in the following sections.
State Machine Diagrams ASET

• States - A state is denoted by a round-cornered rectangle with the


name of the state written inside it.

• Initial and Final States - The initial state is denoted by a filled black circle
and may be labeled with a name. The final state is denoted by a circle with
a dot inside and may also be labeled with a name.
State Machine Diagrams ASET

• Transitions - Transitions from one state to the next are denoted by lines
with arrowheads. A transition may have a trigger, a guard and an effect, as
below.
• Self-Transitions - A state can have a transition that returns to itself, as in
the following diagram. This is most useful when an effect is associated
with the transition.

• "Trigger" is the cause of the transition, which could be a signal, an event, a


change in some condition, or the passage of time. "Guard" is a condition
which must be true in order for the trigger to cause the transition. "Effect"
is an action which will be invoked directly on the object that owns the
state machine as a result of the transition.
ASET

• State Actions - In the transition example above, an effect was associated


with the transition. If the target state had many transitions arriving at it,
and each transition had the same effect associated with it, it would be
better to associate the effect with the target state rather than the
transitions. This can be done by defining an entry action for the state. The
diagram below shows a state with an entry action and an exit action.

• It is also possible to define actions that occur on events, or actions that


always occur. It is possible to define any number of actions of each type.
State Machine Diagrams ASET

• Compound States - A state machine diagram may include sub-


machine diagrams, as in the example below.

Alternative way to
show the same
information
•The ∞ symbol indicates that details of the Check PIN
sub-machine are shown in a separate diagram.
State Machine Diagrams ASET

• Entry Point - Sometimes you won’t want to enter a sub-machine at the


normal initial state. For example, in the following sub-machine it would
be normal to begin in the "Initializing" state, but if for some reason it
wasn’t necessary to perform the initialization, it would be possible to
begin in the "Ready" state by transitioning to the named entry point.

• Exit Point - In a similar manner to entry points, it is possible to have


named alternative exit points. The following diagram gives an example
where the state executed after the main processing state depends on
which route is used to transition out of the state.
State Machine Diagrams ASET

• Choice Pseudo-State - A choice pseudo-state is shown as a


diamond with one transition arriving and two or more transitions
leaving. The following diagram shows that whichever state is arrived
at, after the choice pseudo-state, is dependent on the message
format selected during execution of the previous state.
State Machine Diagrams ASET

• Junction Pseudo-State - Junction pseudo-states are used to chain together


multiple transitions. A single junction can have one or more incoming, and one
or more outgoing, transitions; a guard can be applied to each transition.
Junctions are semantic-free. A junction which splits an incoming transition into
multiple outgoing transitions realizes a static conditional branch, as opposed to
a choice pseudo-state which realizes a dynamic conditional branch.
State Machine Diagrams
ASET
• Terminate Pseudo-State - Entering a terminate pseudo-state
indicates that the lifeline of the state machine has ended. A
terminate pseudo-state is notated as a cross.

• History States - A history state is used to remember the previous state of a


state machine when it was interrupted. The following diagram illustrates
the use of history states. The example is a state machine belonging to a
washing machine.
State Machine Diagrams ASET

• Concurrent Regions - A state may be divided into regions containing sub-


states that exist and execute concurrently. The example below shows that
within the state "Applying Brakes", the front and rear brakes will be
operating simultaneously and independently. Notice the use of fork and
join pseudo-states, rather than choice and merge pseudo-states. These
symbols are used to synchronize the concurrent threads.

You might also like