1 patterns in object oriented programming a concise introductory presentation amnon h. eden tel aviv...

60
1 Patterns in Object Oriented Programming A Concise Introductory Presentation Amnon H. Eden Tel Aviv University [email protected] http://www.math.tau.ac.il/~eden Copyrights All Rights Reserved No 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.

Upload: raquel-grief

Post on 16-Dec-2015

220 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: 1 Patterns in Object Oriented Programming A Concise Introductory Presentation Amnon H. Eden Tel Aviv University eden@math.tau.ac.il eden

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.

Page 2: 1 Patterns in Object Oriented Programming A Concise Introductory Presentation Amnon H. Eden Tel Aviv University eden@math.tau.ac.il eden

2

ContentsContents

Prologue: Motivation

1. Historical perspective

2. Terminology and taxonomy

3. Design patterns

4. Summary

Epilogue: Future directions

Appendix: References

Page 3: 1 Patterns in Object Oriented Programming A Concise Introductory Presentation Amnon H. Eden Tel Aviv University eden@math.tau.ac.il eden

3

A ClaimA Claim

Today, design patterns make

the most effective technique

of conducting and training

OOD !

Page 4: 1 Patterns in Object Oriented Programming A Concise Introductory Presentation Amnon H. Eden Tel Aviv University eden@math.tau.ac.il eden

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

Page 5: 1 Patterns in Object Oriented Programming A Concise Introductory Presentation Amnon H. Eden Tel Aviv University eden@math.tau.ac.il eden

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)

Page 6: 1 Patterns in Object Oriented Programming A Concise Introductory Presentation Amnon H. Eden Tel Aviv University eden@math.tau.ac.il eden

6

Motivation IIIMotivation III

Patterns are about

conveying

skill and experience

Page 7: 1 Patterns in Object Oriented Programming A Concise Introductory Presentation Amnon H. Eden Tel Aviv University eden@math.tau.ac.il eden

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

Page 8: 1 Patterns in Object Oriented Programming A Concise Introductory Presentation Amnon H. Eden Tel Aviv University eden@math.tau.ac.il eden

8

Christopher AlexanderChristopher Alexander

An architect

Relate publications: The Timeless Way of

Building (1979) A Pattern Language

(1977)

Page 9: 1 Patterns in Object Oriented Programming A Concise Introductory Presentation Amnon H. Eden Tel Aviv University eden@math.tau.ac.il eden

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

Page 10: 1 Patterns in Object Oriented Programming A Concise Introductory Presentation Amnon H. Eden Tel Aviv University eden@math.tau.ac.il eden

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

Page 11: 1 Patterns in Object Oriented Programming A Concise Introductory Presentation Amnon H. Eden Tel Aviv University eden@math.tau.ac.il eden

11

Part 2: Part 2: TaxonomyTaxonomy

Terms: Pattern Pattern language

Related terms: Design Architecture Framework Library Component

Page 12: 1 Patterns in Object Oriented Programming A Concise Introductory Presentation Amnon H. Eden Tel Aviv University eden@math.tau.ac.il eden

12

Domain Specific PatternsDomain Specific Patterns

Communications and distributed

processing

Operating systems and processes

Business

Reactive systems

MMI-application interaction

Page 13: 1 Patterns in Object Oriented Programming A Concise Introductory Presentation Amnon H. Eden Tel Aviv University eden@math.tau.ac.il eden

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”

Page 14: 1 Patterns in Object Oriented Programming A Concise Introductory Presentation Amnon H. Eden Tel Aviv University eden@math.tau.ac.il eden

14

Dominant Pattern Domains Dominant Pattern Domains

Design patterns !

Architectural Patterns?

Page 15: 1 Patterns in Object Oriented Programming A Concise Introductory Presentation Amnon H. Eden Tel Aviv University eden@math.tau.ac.il eden

15

Presenting a PatternPresenting a Pattern

The common form:

Name

Intent

Solution

Consequences

Other authors:

Name

Problem

[Context]

[Forces]

Solution

Page 16: 1 Patterns in Object Oriented Programming A Concise Introductory Presentation Amnon H. Eden Tel Aviv University eden@math.tau.ac.il eden

16

Part 3: Part 3: Design PatternsDesign Patterns

The Gang of Four

Examples

Definitions

Observations and conventions

Summary

Page 17: 1 Patterns in Object Oriented Programming A Concise Introductory Presentation Amnon H. Eden Tel Aviv University eden@math.tau.ac.il eden

17

TheThe Gang of Four Gang of Four

Erich GammaRichard HelmRalph JohnsonJohn Vlissides

Design Patterns: Elements of Reusable Object Oriented Software (1995).

Page 18: 1 Patterns in Object Oriented Programming A Concise Introductory Presentation Amnon H. Eden Tel Aviv University eden@math.tau.ac.il eden

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

Page 19: 1 Patterns in Object Oriented Programming A Concise Introductory Presentation Amnon H. Eden Tel Aviv University eden@math.tau.ac.il eden

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

. . .

Page 20: 1 Patterns in Object Oriented Programming A Concise Introductory Presentation Amnon H. Eden Tel Aviv University eden@math.tau.ac.il eden

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( )

Page 21: 1 Patterns in Object Oriented Programming A Concise Introductory Presentation Amnon H. Eden Tel Aviv University eden@math.tau.ac.il eden

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

Page 22: 1 Patterns in Object Oriented Programming A Concise Introductory Presentation Amnon H. Eden Tel Aviv University eden@math.tau.ac.il eden

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

Page 23: 1 Patterns in Object Oriented Programming A Concise Introductory Presentation Amnon H. Eden Tel Aviv University eden@math.tau.ac.il eden

23

ForcesForces

1. The image is expensive to load

2. The complete image is not always necessary

2MB 2KB

optimize!

Page 24: 1 Patterns in Object Oriented Programming A Concise Introductory Presentation Amnon H. Eden Tel Aviv University eden@math.tau.ac.il eden

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: . . .

Page 25: 1 Patterns in Object Oriented Programming A Concise Introductory Presentation Amnon H. Eden Tel Aviv University eden@math.tau.ac.il eden

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

Page 26: 1 Patterns in Object Oriented Programming A Concise Introductory Presentation Amnon H. Eden Tel Aviv University eden@math.tau.ac.il eden

26

ProxyProxy Solution (example): Solution (example):Object DiagramObject Diagram

aDocumentimage

Proxy

theBitmap: RealImage

1: DrawDetailed ( )

3: new (fileName)

2: get_image ( )

4: DrawDetailed( )

Page 27: 1 Patterns in Object Oriented Programming A Concise Introductory Presentation Amnon H. Eden Tel Aviv University eden@math.tau.ac.il eden

27

Proxy Solution (general form)Proxy Solution (general form)

RealSubjectRequest( ) Proxy

Request( )

SubjectRequest( )

client

realSubject

Page 28: 1 Patterns in Object Oriented Programming A Concise Introductory Presentation Amnon H. Eden Tel Aviv University eden@math.tau.ac.il eden

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

Page 29: 1 Patterns in Object Oriented Programming A Concise Introductory Presentation Amnon H. Eden Tel Aviv University eden@math.tau.ac.il eden

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.)

Page 30: 1 Patterns in Object Oriented Programming A Concise Introductory Presentation Amnon H. Eden Tel Aviv University eden@math.tau.ac.il eden

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

Page 31: 1 Patterns in Object Oriented Programming A Concise Introductory Presentation Amnon H. Eden Tel Aviv University eden@math.tau.ac.il eden

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 *)

Page 32: 1 Patterns in Object Oriented Programming A Concise Introductory Presentation Amnon H. Eden Tel Aviv University eden@math.tau.ac.il eden

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)

Page 33: 1 Patterns in Object Oriented Programming A Concise Introductory Presentation Amnon H. Eden Tel Aviv University eden@math.tau.ac.il eden

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)

Page 34: 1 Patterns in Object Oriented Programming A Concise Introductory Presentation Amnon H. Eden Tel Aviv University eden@math.tau.ac.il eden

34

StrategyStrategy sample: sample: I Intersection Traffic Lights Control Traffic Lights Control

The light- switching policy changes by the hour

Page 35: 1 Patterns in Object Oriented Programming A Concise Introductory Presentation Amnon H. Eden Tel Aviv University eden@math.tau.ac.il eden

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

Page 36: 1 Patterns in Object Oriented Programming A Concise Introductory Presentation Amnon H. Eden Tel Aviv University eden@math.tau.ac.il eden

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: …

}

Page 37: 1 Patterns in Object Oriented Programming A Concise Introductory Presentation Amnon H. Eden Tel Aviv University eden@math.tau.ac.il eden

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

Page 38: 1 Patterns in Object Oriented Programming A Concise Introductory Presentation Amnon H. Eden Tel Aviv University eden@math.tau.ac.il eden

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)

Page 39: 1 Patterns in Object Oriented Programming A Concise Introductory Presentation Amnon H. Eden Tel Aviv University eden@math.tau.ac.il eden

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

Page 40: 1 Patterns in Object Oriented Programming A Concise Introductory Presentation Amnon H. Eden Tel Aviv University eden@math.tau.ac.il eden

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);}

Page 41: 1 Patterns in Object Oriented Programming A Concise Introductory Presentation Amnon H. Eden Tel Aviv University eden@math.tau.ac.il eden

41

Part 4: Part 4: Design Patterns - SummaryDesign Patterns - Summary

Perspectives

Observations

Types of design patterns

The Merits of Patterns

Page 42: 1 Patterns in Object Oriented Programming A Concise Introductory Presentation Amnon H. Eden Tel Aviv University eden@math.tau.ac.il eden

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

Page 43: 1 Patterns in Object Oriented Programming A Concise Introductory Presentation Amnon H. Eden Tel Aviv University eden@math.tau.ac.il eden

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 *)

Page 44: 1 Patterns in Object Oriented Programming A Concise Introductory Presentation Amnon H. Eden Tel Aviv University eden@math.tau.ac.il eden

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

Page 45: 1 Patterns in Object Oriented Programming A Concise Introductory Presentation Amnon H. Eden Tel Aviv University eden@math.tau.ac.il eden

45

Perspectives IVPerspectives IV

Patterns are of different levels of abstraction

Pattern A

Pattern B Pattern C Pattern C

Page 46: 1 Patterns in Object Oriented Programming A Concise Introductory Presentation Amnon H. Eden Tel Aviv University eden@math.tau.ac.il eden

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)

Page 47: 1 Patterns in Object Oriented Programming A Concise Introductory Presentation Amnon H. Eden Tel Aviv University eden@math.tau.ac.il eden

47

Summary: Summary: The Merits of PatternsThe Merits of Patterns

Page 48: 1 Patterns in Object Oriented Programming A Concise Introductory Presentation Amnon H. Eden Tel Aviv University eden@math.tau.ac.il eden

48

Merits of Patterns I:Merits of Patterns I: Higher Level of Abstraction

Page 49: 1 Patterns in Object Oriented Programming A Concise Introductory Presentation Amnon H. Eden Tel Aviv University eden@math.tau.ac.il eden

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

Page 50: 1 Patterns in Object Oriented Programming A Concise Introductory Presentation Amnon H. Eden Tel Aviv University eden@math.tau.ac.il eden

50

Merits of Patterns III:Merits of Patterns III:

Improve all Forms of Communicationdocumenting

group planning and design

presenting or learning an existing systemPattern

Page 51: 1 Patterns in Object Oriented Programming A Concise Introductory Presentation Amnon H. Eden Tel Aviv University eden@math.tau.ac.il eden

51

Merits of Patterns IV:Merits of Patterns IV:TrainingTraining

dissemination of solutions

recording the expert’s experience

Page 52: 1 Patterns in Object Oriented Programming A Concise Introductory Presentation Amnon H. Eden Tel Aviv University eden@math.tau.ac.il eden

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

Page 53: 1 Patterns in Object Oriented Programming A Concise Introductory Presentation Amnon H. Eden Tel Aviv University eden@math.tau.ac.il eden

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

Page 54: 1 Patterns in Object Oriented Programming A Concise Introductory Presentation Amnon H. Eden Tel Aviv University eden@math.tau.ac.il eden

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?

Page 55: 1 Patterns in Object Oriented Programming A Concise Introductory Presentation Amnon H. Eden Tel Aviv University eden@math.tau.ac.il eden

55

Appendix: ReferencesAppendix: References

Books

Articles

Page 56: 1 Patterns in Object Oriented Programming A Concise Introductory Presentation Amnon H. Eden Tel Aviv University eden@math.tau.ac.il eden

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.

Page 57: 1 Patterns in Object Oriented Programming A Concise Introductory Presentation Amnon H. Eden Tel Aviv University eden@math.tau.ac.il eden

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

Page 58: 1 Patterns in Object Oriented Programming A Concise Introductory Presentation Amnon H. Eden Tel Aviv University eden@math.tau.ac.il eden

58

Web SitesWeb Sites

Patterns home page:http://hillside.net/patterns/patterns.html

Page 59: 1 Patterns in Object Oriented Programming A Concise Introductory Presentation Amnon H. Eden Tel Aviv University eden@math.tau.ac.il eden

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.

Page 60: 1 Patterns in Object Oriented Programming A Concise Introductory Presentation Amnon H. Eden Tel Aviv University eden@math.tau.ac.il eden

60

Discussion GroupsDiscussion Groups

Discussion groups:– Tel Aviv– New York– Washington– Florida– Stockholm