lecture 20: design patterns ii - unc charlotte...prototype singleton adapter (object) bridge...
TRANSCRIPT
Lecture 20:Design Patterns II
Software System Design and ImplementationITCS/ITIS 6112/8112 001
Fall 2008
Dr. Jamie PaytonDepartment of Computer Science
University of North Carolina at Charlotte
Nov. 13, 2008
2
Design Patterns
A pattern is a way of reusing abstract knowledge about design
a description of the problemthe essence of its solution
Patterns allow programmers to share knowledge about design
3
Alexander’s Patterns
Different Chairs (251)...People are different sizes; they sit in different ways. And yet there is a tendency in modern times to make all chairs alike. ...therefore Never furnish any place with chairs that are identically the same. Choose a variety of different chairs, some big, some small, somesofter than others, some rockers, some very old, some new, with arms, without arms, some wicker, some wood, some cloth.
4
Pattern Elements
NameA meaningful pattern identifier
Problem description (Applicability)Solution description
Not a concrete design……instead, a template for a design solution
ConsequencesThe results and trade-offs of applying the pattern
5
Purpose of Patterns
BehavioralDescribe how classes or objects interact and distribute responsibility• Observer (last time)• Mediator
StructuralDescribe how classes or objects should be composed• Façade• Adapter• Proxy
CreationalConcern the process of object creation• Factory method• Abstract Factory
6
Scope of Patterns
ScopeAnother dimension for classifying patternsClass patterns• Relationships between classes and subclasses
Established through inheritanceFixed at compile-time
Object patterns• Relationships between objects
Changeable at run-time(most patterns)
7
Purpose and ScopeBehavioral
Class• Use inheritance to describe algorithms and flow of controlObject• Describe how a group of objects cooperate to perform a task
StructuralClass• Use inheritance to compose classesObject• Describe how to compose objects
CreationalClass• Defer some part of object creation to a subclassObject• Defer some part of object creation to another object
8
Scope Purpose
Creational Structural Behavioral
Class Factory Method Adapter (class) InterpreterTemplate Method
Object Abstract FactoryBuilderPrototypeSingleton
Adapter (object)BridgeCompositeDecoratorFaçadeProxyFlyweight
Chain of ResponsibilityCommandIteratorMediatorMementoObserverStateStrategyVisitor
9
Boggle
Let’s design an networked Boggle gamePlayers find words in the jumble of letters on the board within given time framePlayer gets one point for each identified real word that is unique• unique = not found by another player
Player with most points wins
What are the basic classes? (ignore the user interface for now)
How do they work together?How should we keep score?
10
Scoring in the Players
Problems?Now every player object has to know about:• Board• Player• Dictionary• EVERY OTHER PLAYER
Tightly coupled!!!
Scoring algorithm is in the player class• May not be the best place for it
Not cohesive!!!
11
Mediator Pattern (1)
ApplicabilityComplex interaction existsYou do not want to bury the interaction in the objectsDistributed behavior should be customizable
SolutionIntroduce a mediator class that is responsible for controlling and coordinating group of objectsObjects refer only to mediator, not each other
12
Mediator (2)
ParticipantsMediator (interface)• Defines interface for communicating with Colleagues
Concrete Mediator• Coordinates Colleague objects• Knows and maintains Colleagues
Colleague• Each Colleague knows its Mediator• Each Colleague communicates with Mediator instead of
Colleagues
13
Mediator (3)
ConsequencesDecouples colleaguesAbstracts how objects cooperateCentralizes control • Simplifies object interaction protocols…• …but can cause a performance hit
Mediator can become complex and unwieldy
14
The Mediator Pattern:Static Structure
15
Mediator-driven Scoring
16
Comparing Boggle Scoring Design Approaches
Without mediatorEach Player must have references to Board, Dictionary, and all Player objects to do scoringScoring algorithm is in Player class• May not really belong there• Complicates Player class
With MediatorPlayer needs references to Board and Tiles only to make playsScoring is in Scorer class• More logically organized, easier to make changes
17
Applying the Mediator Pattern
AnalogiesMeeting SchedulerEmergency Call DispatcherAir Traffic Control CenterChat ApplicationsBoggle
18
Types of Patterns
BehavioralObserverMediator
StructuralFaçadeAdapterProxy
CreationalAbstract Factory
19
Compiler Example
A compilation subsystem consists of:ScannerParserProgramNodeBytecodeStreamProgramNodeBuilder
Most applications that use the compilation subsystem don’t care about the details of these classes
Complicated if the clients have to use the classes directly
20
The Façade Pattern (1)
DescriptionProvide a unified interface to a set of interfaces in a subsystemFacade defines a higher-level interface that makes the subsystem easier to use
21
The Façade Pattern (2)
ApplicabilityNeed to provide a simple interface to a complex systemNeed to decouple a subsystem from its clientsWant to treat subsystem as a software layer• Façade is used as interface to a software layer
22
The Façade Pattern (3)
ParticipantsFaçade• Knows which subsystems classes are responsible for handling a
particular request• Delegates client requests to appropriate subsystem objects
Subsystem classes• Implement subsystem functionality• Handle work assigned by Facade• Have no knowledge of Facade
23
The Façade Pattern (4)
ConsequencesShields clients from subsystem componentsPromotes weak coupling between the subsystem and its clients• Shield clients from changes to subsystems
Only Façade needs to be aware of changes
24
Facade Pattern: Solution
Client Classes
Subsystem classes
Facade
25
Façade Example
AnalogyTravel agent
Design ExampleA friendlier Java Calendar class
26
Mediator and Façade
Mediator coordinates interaction among multiple objects
Defines some function that is not in ColleaguesColleagues know about Mediator
Façade provide a simplified interface to subsystemsSubsystems do not know about Façade
Can think of a Mediator as a multi-way FaçadeObjects involved in interaction subsystemObjects interact with subsystem through Mediator
27
Types of Patterns
BehavioralObserverMediator
StructuralFaçadeAdapterProxy
CreationalAbstract Factory
28
Word Processor Example
Want to build a word-processorNeed to be able to click a “save” button to save workNeed to be able to print a file by clicking “print” button
We have a Button and a ButtonListener class Upon Button click, will notify registered ButtonListeners of event
We have a DocManager class alreadyHas a printDocument() methodCan’t change DocManager; have to use as-is
How can we combine these together?
29
The Adapter Pattern
DescriptionConvert interface of a class into another interface clients expectAdapter lets classes work together that could not otherwise because of incompatible interfaces
ApplicabilityNeed to use an existing class whose interface does not matchNeed to make use of incompatible classes
30
The Adapter Pattern (2)
ParticipantsTarget (ButtonListener)• Defines the domain-specific interface that the Client uses
Client (Button)• Collaborates with objects conforming to the Target interface
Adaptee (DocManager)• Defines an existing interface that needs adapting
Adapter (a new thing we’re creating)• Adapts the interface of Adaptee to the Target Interface
31
The Adapter Pattern: Approaches
Class AdapterAdapter class is a subclass of adaptee• Inherits operations• Overrides operations if needed• Add new operations to provide new interface
Object AdapterAdapter object holds a reference to adaptee• Delegates work to adaptee object
32
The Adapter (Class) Pattern
33
The Adapter (Object) Pattern
34
Class Adapter for Word Processor Example
Button ButtonListener DocManager
MyDocManager
buttonPressed(Event e)buttonPressed(e){print();…}
35
The Adapter Pattern:Consequences
ConsequencesClass adapter • Adapter commits to the concrete Adapter class
Won’t work when we want to adapt a class and its subclasses
• Lets Adapter override some of Adaptee’s behavior• Introduces only one object, no pointer indirection• Cannot block access to public attributes and methods of
AdapteeObject adapter • Lets a single Adapter work with Adaptee and its subclasses• Makes it harder to override Adaptee behavior
Would have to create Adaptee subclass, make Adapter call subclass operations
36
Applying the Adapter Pattern
AnalogyElectrical travel adapters
Design exampleThread safe PriorityQueue
Design choice between Object and Class Adapter• Must use Object Adapter if:
Adaptee has changeable public attributesCannot subclass adapteeCannot override methods of adaptee
37
Adapter versus Facade
Façade Used to provide a simplified interface to a subsystem
AdapterUsed to provide a different interface to a single classUsed when operations with slightly different functionality are needed
38
Types of Patterns
BehavioralObserverMediator
StructuralFaçadeAdapterProxy
CreationalAbstract Factory
39
The Proxy PatternDescription
Provide a placeholder for another object Applicability
Remote proxies• Hide location of objectVirtual proxies • Create expensive objects on demandProtection proxies • Control access to an objectSmart proxies may: • Count number of references to object (so it can be freed)• Load persistent object into memory on first reference• Prevent changes by other objects
40
The Proxy Pattern
41
Proxy Examples
AnalogyATM card substitutes for cashManager sends subordinate to meeting
Design exampleImage manipulation
42
Types of Patterns
BehavioralDescribe how classes interact and distribute responsibility• Observer• Mediator
StructuralDescribe how classes or objects should be composed• Façade• Adapter• Proxy
CreationalConcern the process of object creation• Factory method• Abstract Factory
43
Traffic Simulator
Want to design a traffic simulator to study traffic patterns
We have Road and VehiclesVehicles are of different types• SUV• Compact• MiniVan• MidSizeVehicles should be generated to match expected distributionWhich class should do this?• Road?• Class?• Neither, really
44
The Factory Method Pattern
ApplicabilityClients do not need to know details of object implementation, just need it to implement particular interface
ConsequencesClient does not have to create objects• Created by generator
Allows choice of actual object type at runtime
45
Factory ExamplesAnalogy
Automobile production• SUVs: Ford Explorer, Acura MDX, Subaru OutbackRental car company• Ask for a compact car, but you don’t care if it’s a Civic
Design ExampleVehicle traffic simulator• Vehicle and Road classes• Must randomly create new Vehicle to adhere to expected distribution of
vehicle typesCompact, SUV, Minivan, Truck
• Which class chooses Vehicle type?Road? VehicleFactory!
46
Types of Patterns
BehavioralObserverMediator
StructuralFaçadeAdapterProxy
CreationalFactoryAbstract Factory
47
The Abstract Factory Pattern
DescriptionProvides an interface for creating families of related or dependent objects without specifying their concrete classes
48
The Abstract Factory Pattern (2)
ApplicabilityNeed to abstract from details of implementation of products Need to have multiple families of products Need to enforce families of products that must be used together Need to hide product implementations and just present interfaces
ConsequencesIsolates concrete classes Makes exchanging product families easy Promotes consistency among products Supporting new kinds (in each family) of products is difficult
49
The Abstract Factory Pattern
AbstractFactory
CreateProductA()
CreateProductB()
ConcreteFactory1
Client
ProductA1ProductA2
AbstractProductA
ProductB2 ProductB1
AbstractProductB
ConcreteFactory2
CreateProductA()
CreateProductB()
50
Abstract Factory Example
WidgetFactory
CreateScrollbar()
CreateWindow()
Window
ScrollBarWWidgetFactory
MacWidgetFactory
Client
WWindowMacWindow
MacScrollBar WScrollBar
One for each standard.
51
Factory Method versus Abstract Factory
Abstract Factory uses Factory Method
52
Design patterns are generic, reusable design templatesDesign patterns provide a vocabulary for discussing designThree types of patterns
BehavioralStructuralCreational
Summary
53
Resources
Introduction to Software Engineering DesignChristopher Fox
GoF bookPoSA bookArticles posted on course website