2. Object-Oriented Analysis and Design
About the GoF Design Patterns
N
Gang-of-Four: Gamma, Helm, Johnson, & Vlissides.
Intermediate-level design patterns.
Large Architectural Patterns (example: Broker) Special
Design Patterns (example: State)
Small GRASP Patterns (example: Expert) General
Chapter 23: Gang-of-Four Design Patterns v3.2 2
3. Object-Oriented Analysis and Design
About the GoF Design Patterns
N
(continued)
Three categories.
Creational - How to build problematic objects.
Structural - How to build flexible structures.
Behavioral - How to build powerful behaviors.
Chapter 23: Gang-of-Four Design Patterns v3.2 3
4. Object-Oriented Analysis and Design
Abstract Factory
Problem: Sometimes constructing an object is very Creational
Pattern
complex.
The object is made of many different kinds of complexly
interconnected parts.
The object consists of many parts from one of two or
more sets of compatible parts, but the sets are
incompatible with each other.
Chapter 23: Gang-of-Four Design Patterns v3.2 4
5. Object-Oriented Analysis and Design
Abstract Factory
Creational
Example: Pattern
Constructing user interface widgets in general
(windows, scrollbars, radio button groups, menus,
… ) when there are several widget sets to choose
from (Motif, OpenLook, Presentation Manager, … )
Chapter 23: Gang-of-Four Design Patterns v3.2 5
6. Object-Oriented Analysis and Design
Abstract Factory
Creational
Solution: Create a Pure Fabrication to do the Pattern
construction!
Client
Scrollbar
WidgetFactory
createScrollbar() MotifScrollbar PMScrollbar
createWindow()
Window
MotifWidgetFactory PMWidgetFactory
createScrollbar() createScrollbar()
createWindow() createWindow() MotifWindow PMWindow
Chapter 23: Gang-of-Four Design Patterns v3.2 6
7. Object-Oriented Analysis and Design
Prototype
Creational
Problem: Sometimes constructing an object is Pattern
very complex.
The object is made of many different kinds of
complexly interconnected parts.
There are so many variations and combinations
that the corresponding inheritance hierarchy is
extremely broad.
Chapter 23: Gang-of-Four Design Patterns v3.2 7
9. Object-Oriented Analysis and Design
Prototype (continued)
Solution. Creational
Pattern
Rather than proliferate special-purpose classes, create
a general class and preconfigure a set of constant,
baseline objects.
Clone() these baseline objects as the initial values for your
objects.
AutomobileSpec is the class
ModelCatalog AutomobileSpec
of all of the Prototypes. It has
* the clone() operation. The
actual prototypes are
getModel(name:String) : AutomobileSpec clone() instances of AutomobileSpec
stored by ModelCatalog.
*
Engine Upholstery Doodad
Nitro Fuel Sticky Plush Boring Really Cool
Std Engine
Engine Upholstery Upholstery Doodad Doodad
Chapter 23: Gang-of-Four Design Patterns v3.2 9
10. Object-Oriented Analysis and Design
Singleton
Creational
Problem: When an object is unique, it is tempting to Pattern
globally access it.
But global variables are “bad.”
How can we have direct visibility of the unique object
without global variables?
Chapter 23: Gang-of-Four Design Patterns v3.2 10
11. Object-Oriented Analysis and Design
Singleton (continued)
Creational
Example: Pattern
AutomobileOrder ModelCatalog
???
addFeature() getModel(name:String) : AutomobileSpec
addPackage()
The ModelCatalog is a big, unique object that thousands of
AutomobileOrders would like to easily access.
Chapter 23: Gang-of-Four Design Patterns v3.2 11
12. Object-Oriented Analysis and Design
Singleton (continued)
Creational
Pattern
Solution.
Define the class of the unique object to have a special method,
instance( ).
This method creates the unique object if it does not already exist.
Or, it finds the unique object and returns a reference to it.
A u to m o b ile O r d e r
N o te th e u s e a th e U M L
s t e r e o t y p e " < < s in g le t o n > > " t o
in d ic a te t h a t th e S in g le to n
a d d F e a tu re () p a t t e r n is b e in g u s e d .
a d d P a c k a g e ()
< < s in g le to n > >
M o d e lC a t a lo g M o d e lC a ta lo g P r o x y
th e In s ta n c e
$ in s ta n c e ( ) : M o d e lC a ta lo g ???
g e t M o d e l( n a m e : S t r in g ) : A u t o m o b ile S p e c
Chapter 23: Gang-of-Four Design Patterns v3.2 12
13. Object-Oriented Analysis and Design
Flyweight
Problem: Sometimes it seems necessary to have Structural
Pattern
many copies of a few constant objects.
However, these copies take up a lot of time and space
(creating and destroying them).
If they were shared, performance might improve.
Chapter 23: Gang-of-Four Design Patterns v3.2 13
14. Object-Oriented Analysis and Design
Flyweight
Structural
Example: A Minesweeper game might have Pattern
hundreds of Squares, each with a SquareState.
But, there are only four distinct SquareStates.
contains
Board Square
1 1.. *, 1.. *
1
has
1
SquareState
Unmarked Flagged Questionable Uncovered
Chapter 23: Gang-of-Four Design Patterns v3.2 14
15. Object-Oriented Analysis and Design
Flyweight (continued)
Structural
Solution. Pattern
Preconfigure the set of constant objects and make them
available for shared use.
“Shared use” typically requires:
A dispenser object, like an Abstract Factory.
Parameter visibility to the using object so that Flyweight
object can remain constant.
Chapter 23: Gang-of-Four Design Patterns v3.2 15
16. Object-Oriented Analysis and Design
Flyweight (continued)
Structural
Pattern
uncover
mark
Unmarked Questionable
uncover mark mark
Uncovered Flagged
uncover
mark uncover
Chapter 23: Gang-of-Four Design Patterns v3.2 16
18. Object-Oriented Analysis and Design
Proxy
Problem: Sometimes it is desirable not to directly Structural
Pattern
access an object but, instead, access it
through a placeholder or surrogate.
Typically, this need arises from reliability and/or complexity concerns.
Chapter 23: Gang-of-Four Design Patterns v3.2 18
19. Object-Oriented Analysis and Design
Proxy (continued)
Structural
Examples. Pattern
Remote Proxy - A local presentation of a remote
object.
Virtual Proxy - A lightweight object that creates its
heavyweight object on demand.
Protection Proxy - A sentry that guards a secure object.
Device Proxy - A logical device that manages a physical
device.
Chapter 23: Gang-of-Four Design Patterns v3.2 19
20. Object-Oriented Analysis and Design
Proxy (continued)
Structural
Solution. Pattern
Create an abstract class to specify the logical
interface to the object.
Next, create two subclasses.
One is the Proxy and one is the actual object.
Give the Proxy a reference to the actual object and
make it pass messages through after doing its own
work.
See next page.
Chapter 23: Gang-of-Four Design Patterns v3.2 20
22. Object-Oriented Analysis and Design
Adapter
Problem. Structural
Pattern
Sometimes the interface that you want a client to
use is not the one provided by the supplier.
How can you convert the actual interface of the
supplier to the logical interface of the client?
Chapter 23: Gang-of-Four Design Patterns v3.2 22
23. Object-Oriented Analysis and Design
Adapter (continued)
Structural
Example: Pattern
An AuthorizationRequest is a transaction step, which really
should not be an expert at using a particular kind of modem.
A u t h o r iz a t io n R e q u e s t U S R o b o tic s S p o r ts te r
???
a u th o r iz e ( ) in it ( in it S t r in g )
ta k e O ffh o o k ()
d ia l( p h o n e N u m )
s e n d ( o c t e t S tr in g )
c h e c k C o n n e c t io n ( )
p la c e O n h o o k ( )
Chapter 23: Gang-of-Four Design Patterns v3.2 23
24. Object-Oriented Analysis and Design
Adapter (continued)
Structural
Solution. Pattern
Create an abstract class for a logical interface to
the (category of) device.
Inherit from this interface to create several
adapters, which are experts at using their
corresponding physical devices.
See next page.
Chapter 23: Gang-of-Four Design Patterns v3.2 24
26. Object-Oriented Analysis and Design
Bridge
Structural
Problem. Pattern
Sometimes, logical concepts can get mixed up with
physical concepts in the same inheritance hierarchy.
This is bad.
Often, this situation arises because a family of
concepts have a related family of implementations.
These family trees can cause problems if they are
mixed.
Chapter 23: Gang-of-Four Design Patterns v3.2 26
27. Object-Oriented Analysis and Design
Bridge (continued)
Structural
Example: Pattern
Square
CoveredSquare UncoveredSquare
Plain Flag QueryMark Blank Number Mine
Chapter 23: Gang-of-Four Design Patterns v3.2 27
28. Object-Oriented Analysis and Design
Bridge (continued)
Solution. Structural
Pattern
Separate the two inheritance hierarchies and link them
by a Bridge.
For example, a reference from the logical abstract
class to the physical abstract class.
Cover Square
Plain Flag QueryMark Transparent Blank Number Mine
− Covers represent the user’s guesses about the state of the board.
− Squares contain the actual state of the board.
Chapter 23: Gang-of-Four Design Patterns v3.2 28
29. Object-Oriented Analysis and Design
Facade
Structural
Problem. Pattern
Often groups of classes (and their instances) are
strongly interdependent on each other.
If a client of a cluster of classes (or their instances)
misuses one element of the cluster, then the whole
cluster might become inconsistent.
Chapter 23: Gang-of-Four Design Patterns v3.2 29
30. Object-Oriented Analysis and Design
Façade (continued)
Structural
Example: Pattern
Scheduler
Statistical
ImageRecognizer Board Schedule
Process Control
Inventory Bin Arm
ChipSpec Manipulator PressureSensor
Chapter 23: Gang-of-Four Design Patterns v3.2 30
31. Object-Oriented Analysis and Design
Facade
Solution. Structural
Pattern
Create a Pure Fabrication to be the interface for the
cluster.
The Façade is a composite object that encapsulates
all of the classes/objects in the cluster.
All clients must now send their requests to the
Façade.
See next page.
Chapter 23: Gang-of-Four Design Patterns v3.2 31
32. Object-Oriented Analysis and Design
Façade (continued)
Structural
Im a g e R e c o g n iz e r R obot
S t a t is t ic a l
P ro c e s s C o n tro l
Pattern
In v e n to ry
A s s e m b le r S u b s y s t e m
<<Facade>>
B o a rd
A s s e m b le r
M a n ip u la t o r A r m S u b s y s t e m
S c h e d u le r
<<Facade>>
M a n ip u la r A r m
S c h e d u le
A rm
B in
M a n ip u la t o r P re s s u re S e n s o r
C h ip S p e c
Chapter 23: Gang-of-Four Design Patterns v3.2 32
33. Object-Oriented Analysis and Design
Observer
Problem. Behavioral
Pattern
It is often extremely useful for one object to monitor
the state of another object.
However, the observed object must actually do all the
work.
Also, with more objects monitoring it, the observed
object gets very highly coupled.
Chapter 23: Gang-of-Four Design Patterns v3.2 33
34. Object-Oriented Analysis and Design
Observer (continued)
Behavioral
Example: Pattern
LIS - Resource
LIS - Patron Information
Information
Design Patterns, Gamma et. al. name: CLarman
1994 Addison-Wesley borrowerID: 63910002
callNumber: 94-34264 resources checked out:
status: checked out Design Patterns:94-34264
Java in a Nutshell:94-7463or
(Observer) (Observer)
???
Book
name
callNumber
status (Subject)
Chapter 23: Gang-of-Four Design Patterns v3.2 34
35. Object-Oriented Analysis and Design
Observer (continued)
Warning. Behavioral
Pattern
The classic GoF Observer solution is outdated and
weak.
It should probably not be used in its classic form, as
described in “Design Patterns.”
The idea of publish-subscribe is useful, but the early
1980’s-inspired GoF solution is limited.
Better to replace it with a modern event-based
publish-subscribe form.
Java delegation event model.
Chapter 23: Gang-of-Four Design Patterns v3.2 35
36. Object-Oriented Analysis and Design
Classic Observer
Solution. Behavioral
Pattern
Generalize the behavior of an Observer as an
abstract class.
Give the observed object a collection of concrete observers.
Let the observed object send a generic notification message to the
observers whenever its state changes.
S u b je c t
O b s e rv e r
a d d O b s e rve r(a n O b s e rve r)
1 *
re m o ve O b s e rve r(a n O b s e rve r) m yO b s e rve rs u p d a te ( )
n o t if y O b s e r v e r s ( )
c a lls u p d a t e ( ) o n a ll o f O b s e r v e r is a n a b s tr a c t
th e O b s e r v e r s in it s c la s s . u p d a te ( ) is d e f in e d
c o lle c t io n in th e C o n c r e t e O b s e r v e r
s u b c la s s
B ook
nam e R e s o u r c e I n f o r m a t io n W in d o w
1 1
c a llN u m b e r
s ta tu s m yR e s o u rc e u p d a te ( )
s e tS ta tu s (n e w S ta tu s )
Chapter 23: Gang-of-Four Design Patterns v3.2 36
37. Object-Oriented Analysis and Design
Classic Observer (continued)
Behavioral
Pattern
What are the weaknesses in Classic Observer?
Chapter 23: Gang-of-Four Design Patterns v3.2 37
38. Object-Oriented Analysis and Design
Java Interface and Event-Based Observers
Subject/ «interface»
Source/ EventListener
Publisher
java.awt.Button
1 «interface»
* ActionListener
addActionListener( ActionListener)
removeActionListener( ActionListener ) actionPerformed(ActionEvent)
processActionEvent( ActionEvent )
adds/removes walks through
listeners from collection and sends MyActionListener
a collection. actionPerformed() Observer/
message to each Listener/
listener Subscriber
actionPerformed(ActionEvent)
Chapter 23: Gang-of-Four Design Patterns v3.2 38
39. Object-Oriented Analysis and Design
Java Interface and Event-Based Observers
(continued)
The delegation event model approach to Observer provides
fine-grained notification and low coupling via interfaces.
«interface» «interface»
EventListener EventListener
java.awt.Button
«interface» 1 1 «interface»
MouseListener * * ActionListener
addActionListener( ActionListener)
mouseReleased(MouseEvent) removeActionListener( ActionListener ) actionPerformed(ActionEvent)
addMouseListener( MouseListener)
removeMouseListener( MouseListener )
DavesMouseListener MyActionListener
mouseReleased(MouseEvent) actionPerformed(ActionEvent)
Chapter 23: Gang-of-Four Design Patterns v3.2 39
40. Object-Oriented Analysis and Design
Command
Problem. Behavioral
Pattern
Sometimes requests need to be treated in a more
complex way than as simple messages between
objects.
Client objects might not know exactly which action should be
performed or who should carry out the task.
Requests might need to be queued, performed at a later time, or
sorted based on priority.
New kinds of requests might be added (even at run time.)
Chapter 23: Gang-of-Four Design Patterns v3.2 40
42. Object-Oriented Analysis and Design
Command (continued)
Solution. Behavioral
Pattern
Create an object with a method, execute().
This object is essentially a single method as an object,
except it can carry its own private state.
Menu MenuItem Command
* *
addMenuItem() clicked() execute()
while(moreCommands){ ConcreteCommand1 ConcreteCommand2
commands.execute();
} execute() execute()
Chapter 23: Gang-of-Four Design Patterns v3.2 42
43. Object-Oriented Analysis and Design
State
Problem. Behavioral
Pattern
Sometimes it is necessary for an object’s responses
to messages to vary depending on its state.
Therefore, the meaning of a method depends on the history of
methods previously called.
Chapter 23: Gang-of-Four Design Patterns v3.2 43
44. Object-Oriented Analysis and Design
State (continued)
Example.
Library Information
System
borrowResource(callNum)
enterBorrower(ID)
WaitingForNew Borrowing
Loan Resources
printBorrowReport()
Chapter 23: Gang-of-Four Design Patterns v3.2 44
45. Object-Oriented Analysis and Design
State (continued)
Behavioral
Solution. Pattern
Make the State an abstract class.
Let the specific states inherit from this abstract state.
Give the client object a state object.
See next page.
Chapter 23: Gang-of-Four Design Patterns v3.2 45
46. Object-Oriented Analysis and Design
State (continued)
Behavioral
Pattern
L IS
e n te r B o rro w e r(ID ) L IS S ta te
b o r r o w R e s o u r c e ( c a llN u m )
p r in t B o r r o w R e p o r t ( ) 1 1 e n te rB o rro w e r( ID , L IS )
s e tS ta te (n e w S ta te ) c u r re n tS ta te b o r r o w R e s o u r c e ( C a llN u m , L I S )
r e a lly E n t e r B o r r o w e r ( ID ) p r in t B o r r o w R e p o r t( L IS )
s ta rtN e w L o a n ( ID )
r e a lly B o r r o w R e s o u r c e ( c a llN u m )
r e a lly P r in t R e s o u r c e ( )
W a it in g F o r N e w L o a n L I S S t a t e B o r r o w in g R e s o u r c e s L IS S ta te
e n te rB o r ro w e r (ID ) b o r r o w R e s o u r c e ( C a llN u m )
p r in tB o r r o w R e p o r t( )
Chapter 23: Gang-of-Four Design Patterns v3.2 46
47. Object-Oriented Analysis and Design
State (continued)
Behavioral
The client passes messages through to the state. Pattern
The state chooses its own successor.
enterBorrower(ID) 1:enterBorrower(ID) :WaitingForNew
:LIS
2:idOK:= reallyEnterBorrower(ID) LoanLISState
3[idOK]: startNewLoan(ID) 4:create()
5:setState(newState)
newState:Borrowing
ResourcesLISState
Chapter 23: Gang-of-Four Design Patterns v3.2 47
48. Object-Oriented Analysis and Design
Strategy
Problem. Behavioral
Pattern
Sometimes it can be desirable to have a method
with implementation that changes depending on the
current circumstances.
In other words, it is desirable to use a different algorithm to
accomplish the same task.
The decision must be made at run time.
Chapter 23: Gang-of-Four Design Patterns v3.2 48
50. Object-Oriented Analysis and Design
Strategy (continued)
Solution. Behavioral
Pattern
Create an object for the specific method.
Have the client object pass through to the Strategy.
Inbox
Sorter
sort()
sort()
setStrategy()
SubjectQuickSort DateInsertionSort
sort() sort()
Chapter 23: Gang-of-Four Design Patterns v3.2 50