1
Patternsin Object Oriented Programming
A Concise Introductory Presentation
Amnon H. Eden Tel Aviv University
[email protected]://www.math.tau.ac.il/~eden
Copyrights All Rights ReservedNo part of this document may be reproduced or distributed by any means without the prior written permission of the author. Permission
is granted for individuals to read and use this document for self study.
2
ContentsContents
Prologue: Motivation
1. Historical perspective
2. Terminology and taxonomy
3. Design patterns
4. Summary
Epilogue: Future directions
Appendix: References
3
A ClaimA Claim
Today, design patterns make
the most effective technique
of conducting and training
OOD !
4
Prologue: MotivationPrologue: Motivation
“Software Engineering is an art rather
than science”
“Software Engineering is an art rather
than science”
It requires:
Skill, talent, intelligenceExperience
Creativity, imagination, insight
5
Motivation IIMotivation II
There are about 3000 years of artistic experience to learn from...
…but only some 20 years of experience with OOP! D:Delegator
C1:Concrete_State
Client
F
2: do1(a,b)
1: do1(a,b)
6
Motivation IIIMotivation III
Patterns are about
conveying
skill and experience
7
Part 1: Historical PerspectivePart 1: Historical Perspective
The work of Christopher Alexander Introducing patterns in OOP
– The Hillside group and their work
– A patterns hype
8
Christopher AlexanderChristopher Alexander
An architect
Relate publications: The Timeless Way of
Building (1979) A Pattern Language
(1977)
9
The Work of Christopher AlexanderThe Work of Christopher Alexander
Pattern: “A solution to a problem in a context”.
Pattern language: A set of patterns used to solve closely related problems.
Purpose: – effective reuse– dissemination of solutions
10
Introducing Patterns into OOPIntroducing Patterns into OOP
1987: A workshop in OOPSLA by
Beck & Cunningham
1993: The Hillside Group - Beck,
Cunningham, Coplien, Booch, Johnson, ...
1994: PLoP conference
1995: Design Patterns: Elements of Reusable
Object Oriented Software
11
Part 2: Part 2: TaxonomyTaxonomy
Terms: Pattern Pattern language
Related terms: Design Architecture Framework Library Component
12
Domain Specific PatternsDomain Specific Patterns
Communications and distributed
processing
Operating systems and processes
Business
Reactive systems
MMI-application interaction
13
Language Specific PatternsLanguage Specific Patterns
Also called idioms
C++: Localized Ownership (PLoPD2) Coplien: “Advanced C++ Programming styles
and Idioms”
Smalltalk: Lazy Optimization (PLoPD2) Beck: “Smalltalk Patterns: Best Practices”
14
Dominant Pattern Domains Dominant Pattern Domains
Design patterns !
Architectural Patterns?
15
Presenting a PatternPresenting a Pattern
The common form:
Name
Intent
Solution
Consequences
Other authors:
Name
Problem
[Context]
[Forces]
Solution
16
Part 3: Part 3: Design PatternsDesign Patterns
The Gang of Four
Examples
Definitions
Observations and conventions
Summary
17
TheThe Gang of Four Gang of Four
Erich GammaRichard HelmRalph JohnsonJohn Vlissides
Design Patterns: Elements of Reusable Object Oriented Software (1995).
18
Design pattern: Design pattern: IteratorIterator
Intent: Allow (iterative/sequential)
access to elements of a data structure
Forces: Preserve data abstraction: Do
not expose its internal structure
19
IteratorIterator Example Example
i: List
Iterator
f1:File f2:File f3:File
fileList:
LinkedList
:Link:Link:LinkF
current
Fnext
F
element
Fnext
F
element
F
Ffirst
. . .
20
IteratorIterator: Solution (general form): Solution (general form)
AggregatecreateIterator( )
Insert( )Remove( )
A
Client
Iterator First( )Next( )Prev( )
A
ConcreteAggregate2createIterator( )
Insert( )Remove( )
ConcreteIterator2
First( )Next( )Prev( )
ConcreteAggregate1createIterator( )
Insert( )Remove( )
ConcreteIterator2
First( )Next( )Prev( )
21
Design Pattern: Design Pattern: ProxyProxy
Problem: Defer the cost of object
creation and init. until actually used
Applicability (possible contexts):– Virtual Proxy: Create an expensive object on
demand (lazy construction)– Cache Proxy (PLoPD 2): Hold results temporarily– Remote Proxy: Use a local representative for a
remote object (different address space)– Protection Proxy: Control access to shared object
22
Sample Context: Word ProcessorSample Context: Word Processor
Paragraph
Document
Paragraph
Image
document glyphDraw( )
DrawDetailed( )Position( )A
paragraphDraw( )
DrawDetailed( )
Position( )
imageDraw( )
DrawDetailed( )
Position( )
tableDraw( )
DrawDetailed( )
Position( )
0..n
23
ForcesForces
1. The image is expensive to load
2. The complete image is not always necessary
2MB 2KB
optimize!
24
Anti-PatternAnti-Pattern
Obviously, the document should not be aware to the optimization, nor to the image contents, etc.
document::draw(){ switch (glyph.type) { case image: if (cannot_optimize) load_full_image(); else
optimize(glyph); break; case paragraph: . . .
25
ProxyProxy Solution (example) Solution (example)
Image Proxy|| file_name : String
|| get_image( )Draft( )DrawDetailed( )
Document
Real Image
|| ImageData
Glyph
Draw( ) 0..n
real_image
Solution: Provide a “surrogate” or place-holder which provides transparent access to another object
26
ProxyProxy Solution (example): Solution (example):Object DiagramObject Diagram
aDocumentimage
Proxy
theBitmap: RealImage
1: DrawDetailed ( )
3: new (fileName)
2: get_image ( )
4: DrawDetailed( )
27
Proxy Solution (general form)Proxy Solution (general form)
RealSubjectRequest( ) Proxy
Request( )
SubjectRequest( )
client
realSubject
28
Definitions of Design PatternsDefinitions of Design Patterns
GoF: Description of communicating objects and classes that are
customized to solve a general design in a particular context
Coplien & Schmidt: Design patterns capture the static and dynamic structures of
solutions that occur repeatedly when producing applications in a particular context
29
Design Pattern: Design Pattern: ObserverObserver
Problem: Decouple a data model from “parties” interested in its internal state
Forces– The identity and number of receivers is not
predetermined– Receivers of novel classes may be added to the
system in the future– Polling is inappropriate (too expensive, etc.)
30
Observer Observer Example: File SystemExample: File System
system tem p
windows DOS docum ents
root
Remote File Server
Window in PC 1
root
Windows
temp
system
DOS
Documentsroot
Windows
temp
system
DOS
Documents
Window in PC 2
31
ObserverObserver: Solution: SolutionSubject::Notify(){ for (i = 0; i < _ObsNumber; i++) _my_obs[i]->Update(this);}
ConcreteSubject::ChangeData(){ // Chnage data somehow Notify();}
Observer 1Update(subject *)
ConcreteSubject
ChangeData( )
Observer Update(subject *) = 0
A
SubjectAttach(Observer*)
Detach(Observer *)
Notify()
my_obs10..n
Observer 2Update(subject *)
32
The The ObserverObserver Ignores: Ignores:
How information about the change is conveyedRefining the mechanism for different kinds of changes. . .
Different implementations conform to the same pattern !
(Variations listed in: “Implementation Patterns for the Observer Pattern”, Kim & Benner, PLoPD2)
33
Design pattern: Design pattern: StrategyStrategy
Intent: Let each member of a family of algorithms vary independently from clients that use it
Forces: – input depends on the algorithm– calculations are based on the client’s abstraction
(not using client’s implementation or global data)
34
StrategyStrategy sample: sample: I Intersection Traffic Lights Control Traffic Lights Control
The light- switching policy changes by the hour
35
The Behavior VariesThe Behavior Varies
The “dumb” policy: change the green route every 5 seconds
Midnight policy: change to green whenever a “sensor” detects a vehicle
Rush hour policy: double the “green time” in the busy route
…
36
Anti-PatternAnti-Pattern
Use multiple conditional statement to set the behavior according to current policy
intersection::next_green(the_green_route r){
switch (current_policy) {
case dumb: next_time := time + constant_time;
case midnight: if (not the_green_route.is_busy) then …
case rush_hour: …
}
37
Strategy Strategy Solution (example)Solution (example)
IntersectionTheConstantTime( )
PreviousGreenRoute( )ThisGreenRoute( )
TraficRoutingPolicy
compute_change_time()
DumbPolicycompute_change_time()
MidnightPolicy
compute_change_time()
RushHourPolicy
compute_change_time() EmergencyPolicy
compute_change_time()
current_policy
38
Strategy Strategy Solution (example)Solution (example)Interaction DiagramInteraction Diagram
theIntersectioncurrent_policy: rush_hour
1: compute_change_time(self)
2: const_time ( )
4: change_time_is (2 * 13)
3: const_time_is (13)
39
StrategyStrategy: Consequences: Consequences
Easy to add new strategy (or remove an existing one, etc.)
For instance: From 8 a.m. to 10 a.m. there is no turn left from Dizengof to Arlozorov
40
StrategyStrategy: Consequences II: Consequences II
Easy to factor out similar strategies (using inheritance)
RushHourPolicy
compute_change_time()
MorningRushHour
busy_direction( )
AfternoonRushHour
busy_direction( )
rushHour::compute_change_time(intersection inter){ if (inter.curr_green_route == busy_direction()) return (inter.const_time * 2) else return (inter.const_time);}
41
Part 4: Part 4: Design Patterns - SummaryDesign Patterns - Summary
Perspectives
Observations
Types of design patterns
The Merits of Patterns
42
Perspectives on Patterns IPerspectives on Patterns I
“Each design pattern lets some aspect of system structure vary independently of other aspects, thereby making a system more robust to a particular kind of change.” [GoF 95, p. 24].
For instance:– Observer: the observers vary independently– Strategy: the strategies vary independently– Iterator: the data structures vary independently
43
Perspectives IIPerspectives II
Design patterns are recurring building blocks of rough granularity
X
Y
Z
Observer 1Update(subject *)
ConcreteSubject
ChangeData( )
Observer Update(subject *) = 0
A
SubjectAttach()
Detach(Observer *)
Notify()
my_obs10..n
Observer 2Update(subject *)
44
Perspectives III:Perspectives III:
Patterns Combine & InteractPatterns Combine & Interact
Real
Image
Observer Update(subject *) = 0
A
SubjectAttach()
Detach()
Notify()
1 n
Image ProxyUpdate(Subject *)
Glyph Document
|| file_name : String get_image( )
0..n
45
Perspectives IVPerspectives IV
Patterns are of different levels of abstraction
Pattern A
Pattern B Pattern C Pattern C
46
Observation:Observation:
The specified solution is not always
complete in detail.
Possible reasons:– Context dependent– Language dependent– There are many possible implementations with
similar results (difference does not count)– It cannot be precisely formulated (but only
expressed in natural language)
47
Summary: Summary: The Merits of PatternsThe Merits of Patterns
48
Merits of Patterns I:Merits of Patterns I: Higher Level of Abstraction
49
Merits of Patterns II:Merits of Patterns II: Improved Design
“reuse” ideas (as opposed to pieces of code)
better understanding of mechanisms: do not repeat mistakes or “reinvent the wheel”
RealSubjectRequest( ) Proxy
Request( )
SubjectRequest( )
client
realSubject
50
Merits of Patterns III:Merits of Patterns III:
Improve all Forms of Communicationdocumenting
group planning and design
presenting or learning an existing systemPattern
51
Merits of Patterns IV:Merits of Patterns IV:TrainingTraining
dissemination of solutions
recording the expert’s experience
52
Classifications of Design PatternsClassifications of Design Patterns
Each design pattern dictates structure and/or interaction protocol
Patterns are classified according to structure and/or protocol
Structural: how classes and objects form structures Behavioral: patterns of communications, assigning
responsibilities Creational: abstract the instantiation process
53
Conventions and BeliefsConventions and BeliefsAbout PatternsAbout Patterns
It must be documented in at least 3 distinct
applications before it is a “pattern”
A paper should go through a writer’s
workshop before it is published
It cannot be “coded” in a conventional
OOPL
54
Epilogue: Future DirectionsEpilogue: Future Directions
Open problems: Classification and indexing Tool support Formalization Analysis patterns
Questions: Will patterns survive? Will the industry of patterns converge?
55
Appendix: ReferencesAppendix: References
Books
Articles
56
Collections of PatternsCollections of Patterns
Gamma, Helm, Johnson, Vlissides (1995). Design Patterns:
Elements of Reusable O-O Software
Coplien & Schmidt, eds. (1994). Pattern Languages of Program
Design (AKA PLoPD 1).
Vlissides, Coplien & Kerth, eds. (1995). Pattern Languages of
Program Design 2 (AKA PLoPD 2).
Buschmann et. al (1996). Pattern-Oriented Software Architecture
(AKA The Siemens Book). Martin R., D. Riehle, F. Buschmann, eds. (1997) Pattern
Languages of Program Design 3.
Fowler (1997). Analysis Patterns.
57
PLoP ConferencesPLoP Conferences
PLoP = Pattern Languages of Programming
Twice a year, since 1994: PLoP USA EuroPLoP
Purpose: Promote good pattern papers
Products: PLoPD booksPattern
58
Web SitesWeb Sites
Patterns home page:http://hillside.net/patterns/patterns.html
59
ArticlesArticles
Beck & Johnson 1994. Patterns Generate
Architecture. ECOOP 94
Schmidt D. Overview of Patterns and Pattern
Languages. CACM, Vol. 39, No. 10, October
96.
Vlissides J. To Kill a Singleton. C++ Report,
June 1996.
60
Discussion GroupsDiscussion Groups
Discussion groups:– Tel Aviv– New York– Washington– Florida– Stockholm