Upload
ashish-lijhara
View
188
Download
0
Tags:
Embed Size (px)
Citation preview
OOA&D - v3.2 - English
Gang-of-Four Design Patterns
Chapter 23: Gang-of-Four Design Patterns v3.2 2
Object-Oriented Analysis and Design
Architectural Patterns (example: Broker)Design Patterns (example: State)
GRASP Patterns (example: Expert)Small
Large
General
Special
About the GoF Design Patterns
Gang-of-Four: Gamma, Helm, Johnson, & Vlissides. Intermediate-level design patterns.
N
Chapter 23: Gang-of-Four Design Patterns v3.2 3
Object-Oriented Analysis and Design
About the GoF Design Patterns (continued)
Three categories. Creational - How to build problematic objects. Structural - How to build flexible structures. Behavioral - How to build powerful behaviors.
N
Chapter 23: Gang-of-Four Design Patterns v3.2 4
Object-Oriented Analysis and Design
CreationalPattern
Abstract Factory
Problem: Sometimes constructing an object is very 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 5
Object-Oriented Analysis and Design
Abstract Factory
Example: 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, … )
CreationalPattern
Chapter 23: Gang-of-Four Design Patterns v3.2 6
Object-Oriented Analysis and Design
WidgetFactory
createScrollbar()createWindow()
MotifWidgetFactory
createScrollbar()createWindow()
Client
Scrollbar
MotifScrollbar PMScrollbar
PMWidgetFactory
createScrollbar()createWindow()
Window
MotifWindow PMWindow
Abstract Factory
Solution: Create a Pure Fabrication to do the construction!
CreationalPattern
Chapter 23: Gang-of-Four Design Patterns v3.2 7
Object-Oriented Analysis and Design
Prototype
Problem: Sometimes constructing an object is 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.
CreationalPattern
Chapter 23: Gang-of-Four Design Patterns v3.2 8
Object-Oriented Analysis and Design
97FordEscortGX 97FordEscortLX
97FordTaurusGX 97FordTaurusLX
97ChevyCavalierGS 97ChevyCavalierLX
97ChevyCorsicaGS 97ChevyCorsicaLX
???
Prototype (continued)
Example:Creational
Pattern
Chapter 23: Gang-of-Four Design Patterns v3.2 9
Object-Oriented Analysis and Design
ModelCatalog
getModel(name:String) : AutomobileSpec
AutomobileSpec
clone()
*
Engine Upholstery Doodad
Std EngineNitro Fuel
EngineSticky
UpholsteryPlush
UpholsteryBoring
DoodadReally Cool
Doodad
*
AutomobileSpec is the class of all of the Prototypes. It hasthe clone() operation. Theactual prototypes areinstances of AutomobileSpecstored by ModelCatalog.
Prototype (continued)
Solution. 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.
CreationalPattern
Chapter 23: Gang-of-Four Design Patterns v3.2 10
Object-Oriented Analysis and Design
Singleton
Problem: When an object is unique, it is tempting to globally access it.
But global variables are “bad.” How can we have direct visibility of the unique object
without global variables?
CreationalPattern
Chapter 23: Gang-of-Four Design Patterns v3.2 11
Object-Oriented Analysis and Design
ModelCatalog
getModel(name:String) : AutomobileSpec
AutomobileOrder
addFeature()addPackage()
???
The ModelCatalog is a big, unique object that thousands of AutomobileOrders would like to easily access.
Singleton (continued)
Example:Creational
Pattern
Chapter 23: Gang-of-Four Design Patterns v3.2 12
Object-Oriented Analysis and Design
<<singleton>>ModelCatalog
$instance() : ModelCataloggetModel(name:String) : AutomobileSpec
AutomobileOrder
addFeature()addPackage()
ModelCatalogProxy
???theInstance
Note the use a the UMLstereotype "<<singleton>>" toindicate that the Singletonpattern is being used.
Singleton (continued)
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.
CreationalPattern
Chapter 23: Gang-of-Four Design Patterns v3.2 13
Object-Oriented Analysis and Design
StructuralPattern
Flyweight
Problem: Sometimes it seems necessary to have 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 14
Object-Oriented Analysis and Design
Board Square
SquareState
Unmarked Flagged Questionable Uncovered
has
contains
1
1
1 1..*,1..*
Flyweight
Example: A Minesweeper game might have hundreds of Squares, each with a SquareState.
But, there are only four distinct SquareStates.
StructuralPattern
Chapter 23: Gang-of-Four Design Patterns v3.2 15
Object-Oriented Analysis and Design
Flyweight (continued)
Solution. 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.
StructuralPattern
Chapter 23: Gang-of-Four Design Patterns v3.2 16
Object-Oriented Analysis and Design
Unmarked Questionable
Uncovered Flagged
mark mark
mark
uncover
uncover
uncover
uncovermark
Flyweight (continued)
StructuralPattern
Chapter 23: Gang-of-Four Design Patterns v3.2 17
Object-Oriented Analysis and Design
Flyweight (continued)
:Unmarked :Squaremark(s:Square) 2: changeState(next)
1: next := getNextState()
FlyweightFactory
buildStates()getState(aStateName) : SquareState
SquareState
mark(s:Square)uncover(s:Square)
theStateSet
1 *
StructuralPattern
Chapter 23: Gang-of-Four Design Patterns v3.2 18
Object-Oriented Analysis and Design
StructuralPattern
Proxy
Problem: Sometimes it is desirable not to directly 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 19
Object-Oriented Analysis and Design
StructuralPattern
Proxy (continued)
Examples. 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 20
Object-Oriented Analysis and Design
Proxy (continued)
Solution. 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.
StructuralPattern
Chapter 23: Gang-of-Four Design Patterns v3.2 21
Object-Oriented Analysis and Design
Proxy (continued)
Printer
status : { online ,outofpaper , jammed }
print(psFile)
Document
print()
RealPrinter
status ??? : { online ,outofpaper , jammed }
print(psFile)
PrinterProxy
status : { online ,outofpaper , jammed }
print(psFile)
StructuralPattern
Chapter 23: Gang-of-Four Design Patterns v3.2 22
Object-Oriented Analysis and Design
StructuralPattern
Adapter
Problem. 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 23
Object-Oriented Analysis and Design
USRoboticsSportster
init(initString)takeOffhook()dial(phoneNum)send(octetString)checkConnection()placeOnhook()
AuthorizationRequest
authorize()
???
An AuthorizationRequest is a transaction step, which really should not be an expert at using a particular kind of modem.
StructuralPattern
Adapter (continued)
Example:
Chapter 23: Gang-of-Four Design Patterns v3.2 24
Object-Oriented Analysis and Design
StructuralPattern
Adapter (continued)
Solution. 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 25
Object-Oriented Analysis and Design
StructuralPattern
Adapter (continued)
SerialCommPort
send(msg,destination)
AuthorizationRequest
authorize()
3ComEthernet10/100
setParms(...)send(buffer,address)broadcast(buffer)
3ComEthernetAdapter
send(msg,address)adaptee
USRoboticsSportster
init(initString)takeOffhook()dial(phoneNum)send(octetString)checkConnection()placeOnhook()
USRModemAdapter
send(msg,phoneNum)adaptee
Chapter 23: Gang-of-Four Design Patterns v3.2 26
Object-Oriented Analysis and Design
StructuralPattern
Bridge
Problem. 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 27
Object-Oriented Analysis and Design
Square
CoveredSquare UncoveredSquare
Flag QueryMarkPlain Number MineBlank
StructuralPattern
Bridge (continued)
Example:
Chapter 23: Gang-of-Four Design Patterns v3.2 28
Object-Oriented Analysis and Design
Square
Number MineBlankFlag QueryMarkPlain
Cover
Transparent
Covers represent the user’s guesses about the state of the board. Squares contain the actual state of the board.
StructuralPattern
Bridge (continued)
Solution. 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.
Chapter 23: Gang-of-Four Design Patterns v3.2 29
Object-Oriented Analysis and Design
StructuralPattern
Facade
Problem. 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 30
Object-Oriented Analysis and Design
Arm
Manipulator
Board
Scheduler
Bin
ChipSpec PressureSensor
Schedule
Inventory
ImageRecognizerStatistical
Process Control
StructuralPattern
Façade (continued)
Example:
Chapter 23: Gang-of-Four Design Patterns v3.2 31
Object-Oriented Analysis and Design
StructuralPattern
Facade
Solution. 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 32
Object-Oriented Analysis and Design
StructuralPattern
Façade (continued)
Arm
Manipulator
Board
Scheduler
Bin
ChipSpec
PressureSensor
Schedule
Inventory
ImageRecognizerStatistical
Process Control
<<Facade>>ManipularArm
Assembler Subsystem
<<Facade>>Assembler
Robot
ManipulatorArm Subsystem
Chapter 23: Gang-of-Four Design Patterns v3.2 33
Object-Oriented Analysis and Design
BehavioralPattern
Observer
Problem. 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 34
Object-Oriented Analysis and Design
LIS - ResourceInformation
Design Patterns, Gamma et. al. 1994 Addison-Wesley callNumber: 94-34264 status: checked out
LIS - Patron Information
name: CLarman borrowerID: 63910002 resources checked out: Design Patterns:94-34264 Java in a Nutshell:94-7463or
Book
namecallNumberstatus (Subject)
(Observer)(Observer)???
BehavioralPattern
Observer (continued)
Example:
Chapter 23: Gang-of-Four Design Patterns v3.2 35
Object-Oriented Analysis and Design
BehavioralPattern
Observer (continued)
Warning. 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 36
Object-Oriented Analysis and Design
Subject
addObserver(anObserver)removeObserver(anObserver)notifyObservers( )
Book
namecallNumberstatus
setStatus(newStatus)
Observer
update( )
ResourceInformationW indow
update( )myResource
myObservers
1 *
11
Observer is an abstractclass. update( ) is definedin the Concrete Observersubclass
calls update( ) on all ofthe Observers in itscollection
BehavioralPattern
Classic Observer
Solution. 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.
Chapter 23: Gang-of-Four Design Patterns v3.2 37
Object-Oriented Analysis and Design
BehavioralPattern
Classic Observer (continued)
What are the weaknesses in Classic Observer?
Chapter 23: Gang-of-Four Design Patterns v3.2 38
Object-Oriented Analysis and Design
Java Interface and Event-Based Observers
java.awt.Button
addActionListener( ActionListener)removeActionListener( ActionListener )
processActionEvent( ActionEvent )
*
MyActionListener
actionPerformed(ActionEvent)
adds/removeslisteners froma collection.
walks throughcollection and sendsactionPerformed()message to eachlistener
«interface»ActionListener
actionPerformed(ActionEvent)
«interface»EventListener
Observer/Listener/Subscriber
Subject/Source/Publisher
1
Chapter 23: Gang-of-Four Design Patterns v3.2 39
Object-Oriented Analysis and Design
java.awt.Button
addActionListener( ActionListener)removeActionListener( ActionListener )
addMouseListener( MouseListener)removeMouseListener( MouseListener )
*
MyActionListener
actionPerformed(ActionEvent)
«interface»ActionListener
actionPerformed(ActionEvent)
«interface»EventListener
1*
DavesMouseListener
mouseReleased(MouseEvent)
«interface»MouseListener
mouseReleased(MouseEvent)
«interface»EventListener
1
Java Interface and Event-Based Observers (continued)
The delegation event model approach to Observer providesfine-grained notification and low coupling via interfaces.
Chapter 23: Gang-of-Four Design Patterns v3.2 40
Object-Oriented Analysis and Design
BehavioralPattern
Command
Problem. 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 41
Object-Oriented Analysis and Design
BehavioralPattern
Command (continued)
Example.
Chapter 23: Gang-of-Four Design Patterns v3.2 42
Object-Oriented Analysis and Design
Command
execute()
ConcreteCommand1
execute()
ConcreteCommand2
execute()
Menu
addMenuItem()
MenuItem
clicked()
while(moreCommands){ commands.execute(); }
**
BehavioralPattern
Command (continued)
Solution. 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.
Chapter 23: Gang-of-Four Design Patterns v3.2 43
Object-Oriented Analysis and Design
BehavioralPattern
State
Problem. 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 44
Object-Oriented Analysis and Design
WaitingForNewLoan
BorrowingResources
enterBorrower(ID)
printBorrowReport()
borrowResource(callNum)
Library InformationSystem
State (continued)
Example.
Chapter 23: Gang-of-Four Design Patterns v3.2 45
Object-Oriented Analysis and Design
BehavioralPattern
State (continued)
Solution. 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 46
Object-Oriented Analysis and Design
BehavioralPattern
State (continued)
LIS
enterBorrower(ID)borrowResource(callNum)printBorrowReport()setState(newState)reallyEnterBorrower(ID)startNewLoan(ID)reallyBorrowResource(callNum)reallyPrintResource()
LISState
enterBorrower(ID, LIS)borrowResource(CallNum, LIS)printBorrowReport(LIS)
W aitingForNewLoanLISState
enterBorrower(ID)
BorrowingResourcesLISState
borrowResource(CallNum)printBorrowReport()
1 1
currentState
Chapter 23: Gang-of-Four Design Patterns v3.2 47
Object-Oriented Analysis and Design
:LISenterBorrower(ID) 1:enterBorrower(ID) :WaitingForNewLoanLISState
newState:BorrowingResourcesLISState
4:create()
2:idOK:= reallyEnterBorrower(ID)3[idOK]: startNewLoan(ID)5:setState(newState)
BehavioralPattern
State (continued)
The client passes messages through to the state. The state chooses its own successor.
Chapter 23: Gang-of-Four Design Patterns v3.2 48
Object-Oriented Analysis and Design
BehavioralPattern
Strategy
Problem. 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 49
Object-Oriented Analysis and Design
BehavioralPattern
Strategy (continued)
Example:
Chapter 23: Gang-of-Four Design Patterns v3.2 50
Object-Oriented Analysis and Design
Inbox
sort()setStrategy()
Sorter
sort()
SubjectQuickSort
sort()
DateInsertionSort
sort()
BehavioralPattern
Strategy (continued)
Solution. Create an object for the specific method. Have the client object pass through to the Strategy.