chapter 10, object design ii: patterns and design principles · chapter 10, object design ii:...
TRANSCRIPT
Chapter 10, Object Design II:Patterns and Design Principles
O O
Patterns and Design Principles
Object-Oriented
SoftwareConstruction
Armin B. Cremers, Tobias Rho, Holger Mügge, Daniel Speicher, , g gg , p(based on Bruegge & Dutoit)
Outline of the Lecture
♦ Review of design pattern conceptsWhat is a design pattern?What is a design pattern?Modifiable designsDesign Principlesg p
♦ More patternsObserver: Provide publisher/subscribe mechanismStrategy: Support family of algorithms, separate of policy and mechanismCommand: Encapsulate control flowCommand: Encapsulate control flowAbstract Factory: Provide manufacturer independenceBuilder: Hide a complex creation processBuilder: Hide a complex creation processProxy: Provide Location transparency
Armin B. Cremers, Tobias Rho, Holger Mügge, Daniel Speicher (based on Bruegge & Dutoit) Object-Oriented Software Construction 2
Review: Design pattern
A design pattern is…
…a template solution to a recurring design problemLook before re-inventing the wheel just one more timevariations of the problem and their driving forces
…reusable design knowledgeHigher level than classes or data structures (link lists, binary trees...)Lower level than application frameworksLower level than application frameworksThey provide a shared vocabulary to designers
Armin B. Cremers, Tobias Rho, Holger Mügge, Daniel Speicher (based on Bruegge & Dutoit) Object-Oriented Software Construction 4
…an example of modifiable design
Why are modifiable designs important?p
A modifiable design enables…
…an iterative and incremental development cycleflexibility to change (changing requirements)flexibility to change (changing requirements)concurrent developmentrisk management
…to minimize the introduction of new problems when fixing old onesavoid fragilityavoid fragility
Even small changes can cause cascading effectsCode breaks in unexpected places
locality of change
to deliver more functionality after initial delivery
Armin B. Cremers, Tobias Rho, Holger Mügge, Daniel Speicher (based on Bruegge & Dutoit) Object-Oriented Software Construction 5
…to deliver more functionality after initial delivery
What makes a design modifiable?
♦ Low coupling and high cohesion
coupling
cohesion
♦ Clear dependencies♦ Clear dependencies
♦ Explicit assumptions
Armin B. Cremers, Tobias Rho, Holger Mügge, Daniel Speicher (based on Bruegge & Dutoit) Object-Oriented Software Construction 6
p p
Design Principles, Robert C. Martin, 1996
♦ Dependency Inversion Principle (DIP)Depend upon Abstraction Do NOT Depend upon ConcretionsDepend upon Abstraction, Do NOT Depend upon Concretions.
♦ Acyclic Dependencies Principle (ADP)The dependency structure for a released component must be a Directed Acyclic Graph (DAG). Dependencies must not form cycles.
♦ Stable Dependencies Principle (SDP)The dependencies between components in a design should be in the direction of stability. A component should only depend upon y p y p pcomponents that are more stable than it is.
♦ Stable Abstractions Principle (SAP)♦ Stable Abstractions Principle (SAP)The abstraction of a package should be proportional to its stability! Packages that are maximally stable should be maximally abstract. Instable packages should be concrete.
Armin B. Cremers, Tobias Rho, Holger Mügge, Daniel Speicher (based on Bruegge & Dutoit) Object-Oriented Software Construction 8
DIP/SDP, Robert C. Martin, 1996
Useless ClassMore ReusableTR
ACT
Useless ClassClass
AB
ST
DIP
no cycles!
D
Unmaintainable Cl
Less ReusableClC
RET
E
Class Class
CO
NC
STABLE UNSTABLESDP
Armin B. Cremers, Tobias Rho, Holger Mügge, Daniel Speicher (based on Bruegge & Dutoit) Object-Oriented Software Construction 9
DIP/SDP (Remember these colors! ☺)
Useless ClassMore ReusableTR
ACT
Useless ClassClass
AB
ST
DIP
D
Unmaintainable Cl
Less ReusableClC
RET
E
Class Class
CO
NC
STABLE UNSTABLESDP
Armin B. Cremers, Tobias Rho, Holger Mügge, Daniel Speicher (based on Bruegge & Dutoit) Object-Oriented Software Construction 10
Towards a Pattern Taxonomy
♦ Structural PatternsAdapters, Bridges, Composite, Facades, and Proxies are variations on a single theme:on a single theme:
They reduce the coupling between two or more classes They introduce an abstract class to enable future extensionsThey encapsulate complex structuresThey encapsulate complex structures
♦ Behavioral PatternsConcerned with communication between objectsh l l fl h d ff l f llCharacterize complex control flows that are difficult to follow at
runtimeAssignment of responsibilities between objects
Who does what?♦ Creational Patterns
provide a simple abstraction for a complex instantiation process.p p p pmake the system independent from the way its objects are created, composed and represented
Armin B. Cremers, Tobias Rho, Holger Mügge, Daniel Speicher (based on Bruegge & Dutoit) Object-Oriented Software Construction 11
On to More Patterns!
♦ Behavioral patternObserverObserver StrategyCommandCommand
♦ Creational PatternsAbstract Factory Builder
♦ Structural patternProxy
Armin B. Cremers, Tobias Rho, Holger Mügge, Daniel Speicher (based on Bruegge & Dutoit) Object-Oriented Software Construction 12
A Pattern Taxonomy
Pattern
StructuralPattern
B h i l
CreationalPattern
BehavioralPattern
Command Observer Strategy
AbstractFactory
BuilderPattern
Observer
Ad t B id F d P
Armin B. Cremers, Tobias Rho, Holger Mügge, Daniel Speicher (based on Bruegge & Dutoit) Object-Oriented Software Construction 13
Adapter Bridge Facade Proxy
Review:Model View Controller Framework
a = 50% Controller Model1
1*
b = 30%c = 20%
View
1
*
1
- X - X- X
a = 50%b = 30%c = 20%c 20%
• Multiple views can exist at the same timeNew views can be added without any changes to the model
Armin B. Cremers, Tobias Rho, Holger Mügge, Daniel Speicher (based on Bruegge & Dutoit) Object-Oriented Software Construction 14
• New views can be added without any changes to the model• architectural pattern
Design patterns inside MVC
♦ Propagate change: Observer Patterna = 50%b = 30%c = 20%
Also used in client / server developmentfor the notification of clients - X
♦ Nested Views: Composite PatternA View contains other views, but is used
- X
like a simple viewE.g. used for GUI widgets or parse trees in compiler implementationsin compiler implementations
♦ Reactions on events in the controller: Strategy PatternControllers can be changed at runtimeE.g. used for different GUI controllers (view activated / deactivated)
- X
Armin B. Cremers, Tobias Rho, Holger Mügge, Daniel Speicher (based on Bruegge & Dutoit) Object-Oriented Software Construction 15
(view activated / deactivated)
Observer pattern
♦ “Define a one-to-many dependency between objects so th t h bj t h t t ll it d d tthat when one object changes state, all its dependents are notified and updated automatically.”
♦ Also called “Publish and Subscribe”♦ Also called Publish and Subscribe
♦ Forces / Applicability♦ Forces / ApplicabilityA change to one object requires changes of othersNotification of other objects of unknown structureNotification of other objects of unknown structureMaintaining consistency across redundant stateOptimizing batch changes to maintain consistencyp g g y
Armin B. Cremers, Tobias Rho, Holger Mügge, Daniel Speicher (based on Bruegge & Dutoit) Object-Oriented Software Construction 16
Observer pattern (continued)
Observers Subject
Object Design 2 (Patterns).ppt
Armin B. Cremers, Tobias Rho, Holger Mügge, Daniel Speicher (based on Bruegge & Dutoit) Object-Oriented Software Construction 17
Observer pattern (cont’d)
Observer
d t ()
Subjectattach(observer)
( )
observers *for(Observer o : observers )d t () update()detach(observer)
notify()
o.update();
ConcreteSubjectgetState()
ConcreteObserverupdate()
subjectsetState(newState) {…notify();
} setState(newState)subjectState
observerState}
♦ The Subject represents the actual state, the Observersrepresent different views of the state.Observer can be implemented as a Java interface♦ Observer can be implemented as a Java interface.
♦ Subject is a super class (needs to store the observer set) not an interface
Armin B. Cremers, Tobias Rho, Holger Mügge, Daniel Speicher (based on Bruegge & Dutoit) Object-Oriented Software Construction 18
set) not an interface.
Sequence diagram for scenario: Change filename to “foo”g
aListViewanInfoViewaFile
setState(“foo”)
Attach()Attach()
setState( foo )
notify()
Subject goes through all its observers and calls update() on
them asking for the new
d t ()
notify() them, asking for the new state is decoupled from
the notification
getState()
update()
“foo”
update()
foo
Armin B. Cremers, Tobias Rho, Holger Mügge, Daniel Speicher (based on Bruegge & Dutoit) Object-Oriented Software Construction 19
Animated Sequence diagram
aListViewanInfoViewaFile
Attach()Attach()
setState(“foo”)
notify()
setState( foo )
notify()
d t ()
getState()
update()update()
“foo”
Armin B. Cremers, Tobias Rho, Holger Mügge, Daniel Speicher (based on Bruegge & Dutoit) Object-Oriented Software Construction 20
Observer pattern implementation in Java
// import java.util;
public class Subject extends Object {private HashSet<Observer> observers = new HashSet();public void addObserver(Observer o) { observers.add(o); }public void deleteObserver(Observer o) {…}public void notifyObservers() { forall: o in: observers do: … }public void notifyObservers(Object arg);
}
public abstract interface Observer {bli b t t id d ( b bl bj )public abstract void update(Observable o, Object arg);
}public class ConcreteSubject extends Subject {
public void setState(String filename);public void setState(String filename);public string getState();
}
Armin B. Cremers, Tobias Rho, Holger Mügge, Daniel Speicher (based on Bruegge & Dutoit) Object-Oriented Software Construction 21
Observer enforces Design PrinciplesMotivation
TRAC
TA
BS
T
notifies
TemperatureSensor
notifies
TemperatureDisplay
CR
ETE
Application
p y
CO
NC
STABLE UNSTABLE
Application
Armin B. Cremers, Tobias Rho, Holger Mügge, Daniel Speicher (based on Bruegge & Dutoit) Object-Oriented Software Construction 22
Observer enforces Design PrinciplesSolution
TRAC
T
ObserverA
BS
T Observer
Subjectj
TemperatureSensor
TemperatureDisplay
CR
ETE
Application
p y
CO
NC
STABLE UNSTABLE
Application
We replaced the „bad“ dependency with a common good“ dependency
Armin B. Cremers, Tobias Rho, Holger Mügge, Daniel Speicher (based on Bruegge & Dutoit) Object-Oriented Software Construction 23
with a common „good dependency.
Observer variations
♦ Push / pull model♦ Specifying interest explicitly
Extend subject's registration interfaceSpecify interest for specific events
Improves update efficiency
Change Manager♦ Change-ManagerExample
Operation involves changes to several independent objectsOperation involves changes to several independent objectsChange-Manager postpones notification after all changes have been committed (transaction)
Armin B. Cremers, Tobias Rho, Holger Mügge, Daniel Speicher (based on Bruegge & Dutoit) Object-Oriented Software Construction 24
A Pattern Taxonomy
Pattern
StructuralPattern
Behavioral
CreationalPattern
Pattern
Command Observer Strategy
AbstractFactory
BuilderPattern
Command StrategyCommand
Armin B. Cremers, Tobias Rho, Holger Mügge, Daniel Speicher (based on Bruegge & Dutoit) Object-Oriented Software Construction 25
Adapter Bridge Facade Proxy
Strategy Pattern - Forces
♦ Many different algorithms exists for the same task♦ The different algorithms will be appropriate at different
timesE l♦ Examples:
Breaking a stream of text into linesSorting a list of customersSorting a list of customers
♦ We don’t want to support all the algorithms if we don’t need themneed them
♦ If we need a new algorithm, we want to add it easily without disturbing the application using the algorithmg pp g g
Armin B. Cremers, Tobias Rho, Holger Mügge, Daniel Speicher (based on Bruegge & Dutoit) Object-Oriented Software Construction 26
Strategy Pattern
Policy
StrategyAlgorithmInterface
Context
ContextInterface()
*
ConcreteStrategyCConcreteStrategyBConcreteStrategyA
AlgorithmInterface()AlgorithmInterface()AlgorithmInterface()
d id hi h i b i h
Armin B. Cremers, Tobias Rho, Holger Mügge, Daniel Speicher (based on Bruegge & Dutoit) Object-Oriented Software Construction 27
Policy decides which Strategy is best given the current Context
Applying a Strategy Pattern in a Database Applicationpp
DatabaseStrategy
Sort()
atabase
Search()Sort()
Strategy *
BubbleSort QuickSort MergeSort
Sort() Sort() Sort()
Armin B. Cremers, Tobias Rho, Holger Mügge, Daniel Speicher (based on Bruegge & Dutoit) Object-Oriented Software Construction 28
Applicability of Strategy Pattern
♦ Many related classes differ only in their behaviorconfigure a single class with one of many behaviors
♦ Different variants of an algorithm are needed that trade-off space against timeoff space against time
Implement all variants as a hierarchy of algorithms
Armin B. Cremers, Tobias Rho, Holger Mügge, Daniel Speicher (based on Bruegge & Dutoit) Object-Oriented Software Construction 29
A Pattern Taxonomy
Pattern
StructuralPattern
Behavioral
CreationalPattern
Pattern
Command Observer Strategy
AbstractFactory
BuilderPattern
Command
Armin B. Cremers, Tobias Rho, Holger Mügge, Daniel Speicher (based on Bruegge & Dutoit) Object-Oriented Software Construction 30
Adapter Bridge Facade Proxy
Command Pattern: Motivation
♦ You want to build a user interface ♦ You want to provide menus♦ You want to make the user interface reusable across
li imany applicationsYou cannot hardcode the meanings of the menus for the various applicationsvarious applicationsThe applications only know what has to be done when a menu is selected.
♦ Such a menu can easily be implemented with the Command Pattern
Armin B. Cremers, Tobias Rho, Holger Mügge, Daniel Speicher (based on Bruegge & Dutoit) Object-Oriented Software Construction 31
Command pattern
Command
execute()Invoker
execute()Client
bindsReceiver
action()
ConcreteCommand
execute()
binds
♦ Client creates a ConcreteCommand and binds it with a Receiver
execute()
a Receiver.♦ Client hands the ConcreteCommand over to the
Invoker which stores it.Invoker which stores it.♦ The Invoker has the responsibility to do the command
(“execute” or “undo”).
Armin B. Cremers, Tobias Rho, Holger Mügge, Daniel Speicher (based on Bruegge & Dutoit) Object-Oriented Software Construction 32
Command pattern Applicability
♦ “Encapsulate a request as an object, thereby letting youparameterize clients with different requests,queue or log requests, and support undoable operations.”
♦ Uses:Undo queuesDatabase transaction bufferingdecouple gui and backenddecouple gui and backendComposite commands (macros)
Armin B. Cremers, Tobias Rho, Holger Mügge, Daniel Speicher (based on Bruegge & Dutoit) Object-Oriented Software Construction 33
A Pattern Taxonomy
Pattern
StructuralPattern
Behavioral
CreationalPattern
Pattern
Ab
Command Observer Strategy
AbstractFactory
BuilderPattern
Command Strategy
AbstractFactory
Armin B. Cremers, Tobias Rho, Holger Mügge, Daniel Speicher (based on Bruegge & Dutoit) Object-Oriented Software Construction 36
Adapter Bridge Facade Proxy
Abstract Factory Motivation
♦ 2 Examples♦ Consider a user interface toolkit that supports multiple
looks and feel standards such as Gnome, Windows XP or Aqua OS XAqua OS X.
How can you write a single user interface and make it portable across the different look and feel standards for these window managers?
♦ Consider a facility management system for an intelligent house that supports different control systems such ashouse that supports different control systems such as Siemens’ Instabus or Johnson & Control Metasys.
How can you write a single control system that is independent y g y pfrom the manufacturer?
Armin B. Cremers, Tobias Rho, Holger Mügge, Daniel Speicher (based on Bruegge & Dutoit) Object-Oriented Software Construction 37
Abstract Factory
AbstractProductAClient
AbstractFactory
ProductA1 ProductA2
Client CreateProductACreateProductB
ProductA1 ProductA2
ConcreteFactory1
CreateProductACreateProductB
AbstractProductBConcreteFactory1
ProductB1 ProductB2
CreateProductA
ConcreteFactory2
Initiation Assocation:
Armin B. Cremers, Tobias Rho, Holger Mügge, Daniel Speicher (based on Bruegge & Dutoit) Object-Oriented Software Construction 38
CreateProductACreateProductB
Class ConcreteFactory2 initiates theassociated classes ProductB2 and ProductA2
Applicability for Abstract Factory Pattern
♦ Independence from Initialization or Representation:The system should be independent of how its products are created, y p p ,composed or represented
♦ Manufacturer Independence:A system should be configured with one family of products whereA system should be configured with one family of products, where one has a choice from many different families.You want to provide a class library for a customer (“facility management library”) but you don’t want to reveal what particularmanagement library ), but you don t want to reveal what particular product you are using.
♦ Constraints on related productsA family of related products is designed to be used together and you need to enforce this constraint
♦ Cope with upcoming change:p p g gYou use one particular product family, but you expect that the underlying technology is changing very soon, and new products will appear on the market.
Armin B. Cremers, Tobias Rho, Holger Mügge, Daniel Speicher (based on Bruegge & Dutoit) Object-Oriented Software Construction 39
pp
Example: A Facility Management System for the Intelligent Workplace
IntelligentWorkplace
InitLightSystem
LightBulbFacilityMgt g y
InitBlindSystemInitACSystem
InstabusLight ZumbobelLightC
MgtSystem
Controller Controller
InitLightSystemI i Bli dS
BlindsSiemensFactory
InitBlindSystemInitACSystem
InstabusBlindController
ZumtobelBlindController
InitLightSystem
Metasys
Armin B. Cremers, Tobias Rho, Holger Mügge, Daniel Speicher (based on Bruegge & Dutoit) Object-Oriented Software Construction 40
g yInitBlindsystemInitACSystem
Abstract Factory enforces Design Principlesg p
TRAC
T Blind Bulb
AB
ST
IntelligentWorkspace
I t b Bli d
InstabusLightInstabusLight
InstabusBlind
TE
InstabusBlindInstabusBlind
CO
NC
RET
Facility Mgt System
Armin B. Cremers, Tobias Rho, Holger Mügge, Daniel Speicher (based on Bruegge & Dutoit) Object-Oriented Software Construction 41
C
STABLE UNSTABLE
y
Abstract Factory enforces Design Principlesg p
TRAC
T Blind Bulb
AB
ST
WorkspaceFactory
IntelligentWorkspace
I t b Bli d
InstabusLightInstabusLight
InstabusBlind
TE
InstabusBlindInstabusBlind
SiemensFactorySiemensFactory
CO
NC
RET
Facility Mgt System
SiemensFactoryy
Armin B. Cremers, Tobias Rho, Holger Mügge, Daniel Speicher (based on Bruegge & Dutoit) Object-Oriented Software Construction 42
C
STABLE UNSTABLE
y
A Pattern Taxonomy
Pattern
StructuralPattern
Behavioral
CreationalPattern
Pattern
Command Observer Strategy
AbstractFactory
BuilderPattern
Command Strategy
Builder Pattern
Armin B. Cremers, Tobias Rho, Holger Mügge, Daniel Speicher (based on Bruegge & Dutoit) Object-Oriented Software Construction 43
Adapter Bridge Facade Proxy
Builder Pattern Motivation
♦ Conversion of documents d f f♦ Motivation: A reader for RTF format
Convert RTF to many text formats (Tex, HTML, MS Word 2003 Open Office 2 0 )2003, Open Office 2.0, ….)
Problem: The number of conversions is open-ended.
Armin B. Cremers, Tobias Rho, Holger Mügge, Daniel Speicher (based on Bruegge & Dutoit) Object-Oriented Software Construction 44
Builder Pattern
♦ Applicability / ForcesAlgorithm for creating objects should be independent of the partsConstruction process must allow different representation forConstruction process must allow different representation for the constructed objects
♦ SolutionConfigure the RTF Reader with a “builder” object that specializes in conversions to any known format and can easilyspecializes in conversions to any known format and can easily be extended to deal with any new format appearing on the market
Armin B. Cremers, Tobias Rho, Holger Mügge, Daniel Speicher (based on Bruegge & Dutoit) Object-Oriented Software Construction 45
Builder Pattern
Di t B ild r
Construct()
Director
BuildPart()
Builder
For all objects in Structure {B ild >B ildP ()Builder->BuildPart()
}
ConcreteBuilderB
BuildPart()GetResult()
ConcreteBuilderB
Represen-tation BConcreteBuilderA
BuildPart()GetResult()
ConcreteBuilderA
Represen-t ti A
Armin B. Cremers, Tobias Rho, Holger Mügge, Daniel Speicher (based on Bruegge & Dutoit) Object-Oriented Software Construction 46
tation A
Example
Parse()
RTFReader
ConvertCharacter()
TextConverter
()
While (t = GetNextToken()) {it h (t T ) {
ConvertCharacter()ConvertFontChange()ConvertParagraph()
switch (t.Type) {CHAR: builder->ConvertCharacter(t.Char);FONT: builder->ConvertFont(t.Font);PARA: builder->ConvertParagraph(t.Para);
}}}
A iiC
ConvertCharacter()ConvertFontChange()ConvertParagraph()
AsciiConverter
ConvertCharacter()ConvertFontChange()ConvertParagraph()G T T ()
TexConverter
ConvertCharacter()ConvertFontChange()ConvertParagraph()
HTMLConverter
ConvertParagraph()GetAsciiText()
A iiT t
g pGetTexText() ConvertParagraph()
GetHtmlText()
HTMLT t
Armin B. Cremers, Tobias Rho, Holger Mügge, Daniel Speicher (based on Bruegge & Dutoit) Object-Oriented Software Construction 47
AsciiTextTeXText HTMLText
When do you use the Builder Pattern?
♦ The creation of a complex product must be independent f th ti l t th t k th d tof the particular parts that make up the product
In particular, the creation process should not know about the assembly process (how the parts are put together to make upassembly process (how the parts are put together to make up the product)
Armin B. Cremers, Tobias Rho, Holger Mügge, Daniel Speicher (based on Bruegge & Dutoit) Object-Oriented Software Construction 48
Comparison: Abstract Factory vs Buildery
♦ Abstract Factoryd f ilFocuses on product family
The products can be simple (“light bulb”) or complex (“engine”)
Does not hide the creation processDoes not hide the creation processThe product is immediately returned
♦ BuilderThe underlying product needs to be constructed as part of the system, but the creation is very complexh f h l d h fThe construction of the complex product changes from time to
timeThe builder patterns hides the creation process from the user:The builder patterns hides the creation process from the user:
The product is returned after creation as a final step
♦ Abstract Factory and Builder work well together for a
Armin B. Cremers, Tobias Rho, Holger Mügge, Daniel Speicher (based on Bruegge & Dutoit) Object-Oriented Software Construction 49
family of multiple complex products
Proxy Pattern: Motivation
♦ Imagine you want to set up an internet connection via a GPRS h t it T i ll itGPRS phone to access a news site. Typically news sites are packed with advertising - static pictures and flash animations which take a while to load over a slow a a o a a o oad o a oconnection and make your visit expensive if you pay your connection per KB.
♦ What can you do?
Armin B. Cremers, Tobias Rho, Holger Mügge, Daniel Speicher (based on Bruegge & Dutoit) Object-Oriented Software Construction 50
Proxy Pattern
♦ What is expensive? Object CreationObject Initialization
D f bj i d bj i i i li i h i♦ Defer object creation and object initialization to the time you need the object
♦ Proxy pattern:♦ Proxy pattern:Reduces the cost of accessing objectsUses another object (“the proxy”) that acts as a stand-in forUses another object ( the proxy ) that acts as a stand in for the real objectThe proxy creates the real object only if the user asks for itMaybe a local representative for an object in a different address space.
Armin B. Cremers, Tobias Rho, Holger Mügge, Daniel Speicher (based on Bruegge & Dutoit) Object-Oriented Software Construction 51
Proxy pattern
Subject
R t()Request()
RealSubject
Request()
Proxy
Request()
realSubject
♦ Interface inheritance is used to specify the interface shared by Proxy and RealSubject.y y j
♦ Delegation is used to catch and forward any accesses to the RealSubject (if desired)
♦ Proxy patterns can be used for lazy evaluation and for remote invocation.
b l d h fArmin B. Cremers, Tobias Rho, Holger Mügge, Daniel Speicher (based on Bruegge & Dutoit) Object-Oriented Software Construction 52
♦ Proxy patterns can be implemented with a Java interface.
Proxy Applicability / Forces
♦ Remote ProxyLocal representative for an object in a different address spaceCaching of information: Good if information does not change too oftentoo often
♦ Virtual ProxyObject is too expensive to create or too expensive toObject is too expensive to create or too expensive to downloadProxy is a stand-in
♦ Protection ProxyProxy provides access control to the real object
f l h d ff b h ld h d ffUseful when different objects should have different access and viewing rights for the same document. Example: Grade information for a student shared by
Armin B. Cremers, Tobias Rho, Holger Mügge, Daniel Speicher (based on Bruegge & Dutoit) Object-Oriented Software Construction 53
Example: Grade information for a student shared by administrators, teachers and students.
Proxy Applicability / Forces ( ctd. )
♦ Smart referenceReplacement for bare referencesPerforms additional actions when object is accessedE lExamples
Reference counting ("smart pointers")Loading persistent object into memoryLoading persistent object into memorySynchronization
Armin B. Cremers, Tobias Rho, Holger Mügge, Daniel Speicher (based on Bruegge & Dutoit) Object-Oriented Software Construction 54
Virtual Proxy example
ImageboundingBox()
d ()draw()
realSubjectRealImage
boundingBox()draw()
ProxyImageboundingBox()
draw()
♦ Images are stored and loaded separately from text♦ If a RealImage is not loaded a ProxyImage displays a
l i l f h igrey rectangle in place of the image♦ The client cannot tell that it is dealing with a
ProxyImage instead of a RealImageProxyImage instead of a RealImage♦ A proxy pattern can be easily combined with a Bridge
Armin B. Cremers, Tobias Rho, Holger Mügge, Daniel Speicher (based on Bruegge & Dutoit) Object-Oriented Software Construction 55
Before
Armin B. Cremers, Tobias Rho, Holger Mügge, Daniel Speicher (based on Bruegge & Dutoit) Object-Oriented Software Construction 56
Controlling Access
Armin B. Cremers, Tobias Rho, Holger Mügge, Daniel Speicher (based on Bruegge & Dutoit) Object-Oriented Software Construction 57
After
Armin B. Cremers, Tobias Rho, Holger Mügge, Daniel Speicher (based on Bruegge & Dutoit) Object-Oriented Software Construction 58
Summary
♦ Structural PatternsFocus: How objects are composed to form larger structuresFocus: How objects are composed to form larger structuresProblems solved:
Realize new functionality from old functionality, Provide flexibility and extensibility
♦ Behavioral Patternsl h d h f b lFocus: Algorithms and the assignment of responsibilities to
objectsProblem solved:Problem solved:
Too tight coupling to a particular algorithm
♦ Creational PatternsFocus: Creation of complex objectsProblems solved:
Armin B. Cremers, Tobias Rho, Holger Mügge, Daniel Speicher (based on Bruegge & Dutoit) Object-Oriented Software Construction 59
Hide how complex objects are created and put together
Open-Closed Principle (OCP)(Robert C. Martin)
♦ Classes should be open for extensionthrough inheritance, delegation, observer, …
♦ Classes should be closed for modificationfunctionality (once set) should not be changed
protect correct, bug free code
Sounds contradictory?♦ Sounds contradictory?Examples: Observer, Abstract Factory, Decorator,…
♦ But: Do not apply OCP everywhere!♦ But: Do not apply OCP everywhere!Can lead to complex, hard to understand codeNew levels of abstraction adds complexityNew levels of abstraction adds complexityWasteful and unnecessary
Armin B. Cremers, Tobias Rho, Holger Mügge, Daniel Speicher (based on Bruegge & Dutoit) Object-Oriented Software Construction 60
Conclusion
♦ Design patterns Provide solutions to common problems.L d t t ibl d l d dLead to extensible models and code.Can be used as is or as examples of interface inheritance and delegation.gApply the same principles to structure and to behavior.
♦ Design patterns solve all your software engineering problems
Armin B. Cremers, Tobias Rho, Holger Mügge, Daniel Speicher (based on Bruegge & Dutoit) Object-Oriented Software Construction 61
Recommendations
♦ Freeman & Freeman, head-first design patterns, 638 Pages, O'Reilly & Associates, 2004, ISBN: 0596007124
ll itt i t d tiwell written introductioncomprehensible examplesconcentrates on ten patternsconcentrates on ten patterns
♦ Gamma et al Design Patterns 416 Pages Addison-♦ Gamma et. al., Design Patterns, 416 Pages, Addison-Wesley Professional, 1997, ISBN: 0201633612
Armin B. Cremers, Tobias Rho, Holger Mügge, Daniel Speicher (based on Bruegge & Dutoit) Object-Oriented Software Construction 62