design patterns - a2z dotnet · design patterns dr. uwe assmann pelab (slides derived from walter...

30
Design Patterns Dr. Uwe Assmann PELAB (Slides derived from Walter F. Tichy, Universität Karlsruhe, Germany, Used by permission) 2 Introduction What is a Design Pattern? For what can they be used? How does it look like? Literature: „Design Patterns”, Gamma et al, Addison Wesley,1995 „A System of Patterns”, Buschmann et al, Wiley, 1995. Part II from 2000 „Pattern Languages of Program Design”, Conferences, Addison- Wesley, 1995,... „Software Architecture”, Shaw & Garlan, Prentice Hall, 1996. “Object-oriented Design and Patterns” W. Pree, 1995, Addision- Wesley Special PhD Course Design Patterns (running now)

Upload: phamquynh

Post on 13-Nov-2018

213 views

Category:

Documents


0 download

TRANSCRIPT

Design Patterns

Dr. Uwe AssmannPELAB

(Slides derived from Walter F. Tichy, UniversitätKarlsruhe, Germany, Used by permission)

2

Introduction

n What is a Design Pattern?n For what can they be used?n How does it look like?

n Literature:n „Design Patterns”, Gamma et al, Addison Wesley,1995n „A System of Patterns”, Buschmann et al, Wiley, 1995. Part II

from 2000n „Pattern Languages of Program Design”, Conferences, Addison-

Wesley, 1995,...n „Software Architecture”, Shaw & Garlan, Prentice Hall, 1996.n “Object-oriented Design and Patterns” W. Pree, 1995, Addision-

Wesleyn Special PhD Course Design Patterns (running now)

3

Definition

n A Design Pattern is a description of a standard solutionfor a standard problem in design.

n Goal: Reuse of design informationn A pattern must not be “new”!

4

Alexander’s Laws on Beauty

n Christopher Alexander “The timeless way of building”n a book of the century: A MUST

n Hunting for the “Quality without a name”n Patterns grasp centers of beautyn You have a language for beauty, consisting of patterns

n dependent on culture

n Beauty cannot be invented but must becombined/generated by patterns from a patternlanguage

n Alexander means “composition”

5

Example: Model/View/Controller (MVC)

n -ODEL: Data structure or object, invisiblen 6IEW: Representation(s) on the screenn #ONTROLLER: Encapsulates reactions on inputs of

users, couples model and views

MVC is a agglomeration of classes to control a user interfaceand a data structure (from Smalltalk)

MVC is a complex design pattern and combines the simplerones compositum, strategy, observer.

6

Views as Observer

a=50%b=30%c=20%

7INDOW

a 30 30

10 20 10

b c

10

60 50 80

x y z

7INDOW7INDOW

a b c

Model

7

Model/View/Controller

Relation between model and views is grasped by thedesign pattern /BSERVER.

n Views may register at the model (observers).n They are notified if the model changes. Then, every view

updates itself by accessing the data of the model.n Views are independent of each other. The model does

not know how views visualize it.n /BSERVER decouples strongly.

8

Pattern 2: Compositum

6IEWS�may be NESTED��(#OMPOSITUM)n Example: object inspector in debuggersn Compositum requires that

n The class CompositeView is a subclass of Viewn Can be used in the same way as View

9

Pattern 3: Strategy

The relation between CONTROLLER�and VIEW is a 3TRATEGYpattern�

n There may be different control strategiesn Lazy or eager update of viewsn Menu or keyboard input

n A view may select subclasses of #ONTROLLER��evendynamically

n No other class changes

10

Structure for Design Pattern

n There are several formatsn Gof (Gamma Gang of Four)n Alexandrian format

n Name (incl. Synonyms)n Task and Contextn Solution

n Structure (Components, Relations): UML class or object diagramn Interactions und Consequences: interaction diagramsn Implementation (code examples)

11

The GoF Template

0ATTERN�.AME��3COPE��0URPOSE

The pattern’s name conveys the essence of the pattern succinctly. A good name isvital, because it will become part of your design vocabulary.

)NTENT

A short statement that answers the following questions:

What does the design pattern do? What is its rationale and intent? What particulardesign issue or problem does it address?

!LSO�+NOWN�!S

Other well-known names for the pattern, if any.

-OTIVATION

A scenario that illustrates a design problem and how the class and objectstructures in the pattern solve the problem. The scenario will help youunderstand the more abstract description of the pattern that follows.

12

The GoF Template

!PPLICABILITY

What are the situations in which the design pattern can be applied? What are

examples of poor designs that the pattern can address? How can yourecognize these situations?

3TRUCTURE

A graphical representation of the classes in the pattern.

0ARTICIPANTS

The classes and/or objects participating in the design pattern and their

responsibilities.

#OLLABORATIONS

How the participants collaborate to carry out their responsibilities.

13

The GoF Template

#ONSEQUENCES

How does the pattern support its objectives? What are the trade-offs and results of

using the pattern? What aspect of system structure does it let you vary

independently?

)MPLEMENTATION

What pitfalls, hints, or techniques should you be aware of when implementing the

pattern? Are there language-specific issues?

3AMPLE�#ODE�AND�5SAGE

Code fragments that illustrate how you might implement the pattern in C++ or

Smalltalk.

+NOWN�5SES

Examples of the pattern found in real systems. We include at least two examples

from different domains.

2ELATED�0ATTERNS

What design patterns are closely related to this one? What are the important

differences? With which other patterns should this one be used?

14

A Pattern...

n Describes a single kind of problem.n Describes the context in which the problem occurs.n Describes the solution as a constructable software entity.n Describes design steps or rules for constructing the solution.n Describes the forces leading to the solution.n Describes evidence that the solution optimally resolves forces.n Describes details that are allowed to vary, and those that are not.n Describes at least one actual instance of use.n Describes evidence of generality across different instances.n Describes or refers to variants and subpatterns.n Describes or refers to other patterns that it relies upon.n Describes or refers to other patterns that rely upon this pattern.n Relates to other patterns with similar contexts, problems, or

solutions.

15

Purpose Design Pattern

• Improve communication in teams• Between clients and programmers• Between designers, implementers and testers

• Abstracts design concepts• Patterns are “mini-frameworks”• Documentation• May be used to capture information in reverse engineering

• Improvement of the state of the art of softwareengineering• A “software engineer” without the knowledge of patterns is a

programmer• Fix a glossary for software engineering• Prevent re-invention of well-known solutions

• Improve code quality and structure

16

Design Pattern Categories

n A classification is hardù several are around

n "ASIC�PATTERNS characterize simple collaboration scenarios in classgraphs, sequence diagrams, or other diagrams.n Are used to form larger patterns

n $ATA�PATTERNS characterize state of a set of objects and theirresponsibilities

n #REATIONAL�0ATTERNS determine how objects and object families areallocated

n #OUPLING�PATTERNS �3TRUCTURAL�PATTERNS divide systems intosubsystems such that these can be exchanged independently

n #OMMONALITY�PATTERNS condense common parts of classes intonew classes

n #ONTROL�FLOW�PATTERNS��"EHAVIORAL�PATTERNS describe commoncontrol flow situations

Relations between Patterns

0ROTOTYPE

/BSERVER!BSTRACT�&ACTORY

"UILDER 3TRATEGY ,AYERS

#HAIN/F

2ESPONSIBILITY

6ISITOR

)TERATOR

#OMMAN

"RIDGE

3INGLETON4EMPLATE

-ETHOD

/BJECTIFIER

'LUE-EDIATOR $ECORATOR

#OMPOSITUM

-EMENTO!DAPTER

0ROXY

&LYWEIGHT

$ATA�PATTERNS"ASIC�PATTERNS

&ACADE

#REATION�PATTERNS #OUPLING�PATTERNS #ONTROL�FLOW�PATTERNS

)NTERPRETER

&ACTORY-ETHOD

18

Overview Patterns

n "ASIC�PATTERNS

n TemplateMethod: Vary thealgoritm in a subclass

n Objectifier: Delegate behaviorto special object

n Mediator: Object toencapsulate communication

n Decorator: DynamicExtension of classes

n Proxy: Representant forremote objects

n Compositum: Part/Wholehierarchies

n Adapter: Adapt an interface toanother

n $ATA�PATTERNS

n Singleton: globally uniqueobjects

n Flyweight: Spaceoptimizations byrepresentants

n Memento: Snapshot of state

• #OUPLING�0ATTERNS

• Repository: centralscratchpad

• Facade: encapsulating classfor subsystem

• Layers: layered facades

• Bridge: decouple abstractionfrom implementation

• Observer: event basedcommunication, dynamic

• Event channel: channel ofobservers

• Pipe: stream orientedcommunication

• Framework:

• #ONTROL�FLOW��BEHAVIORAL

PATTERNS

• Visitor: Decouple iterationover tree from actions

• ChainOfResponsibility:cascaded delegation

• Commad: reified commandprocedure

• Blackboard: organizedrepository

• Strategy: algorithm family

• Iterator: iteration withoutknowing internals

• Interpreter

#REATIONAL�0ATTERNS

• FactoryMethod: Vary allocation in subclass

• Abstract Factory: Allocation of object family• Builder:Incremental allocation of complex structured

object

• Prototype: Clone an object

Design Pattern Catalogue

20

Basic Patterns

n According to [W. Zimmer: Frameworks und DesignPattern, PhD 1997 Universität Karlsruhe] DesignPattern can be build from the following basic ones:

n TemplateMethodn Objectifier (Delegation)n Mediatorn Gluen Decoratorn Proxyn Compositumn Adapter

n Data Patternsn Singleton (singleton)n Flyweightn Memento

21

Template Method

...primitiveOperation1();...primitiveOperation2();...

!BSTRACT#LASS

TemplateMethod()PRIMITIVE/PERATION��

PRIMITIVE/PERATION��

#ONCRETE#LASS

primitiveOperation1()primitiveOperation2()

Define the skeleton of an algorithm (template method)Delegate parts to HOOK�METHODS that are filled by subclassesAllows to vary behavior.

22

Template Method

n Separate invariant from variant parts of an algorithmn Factor out common code into superclasses

n Avoid code replacement

n Control extensions by only allowing “hook methods”

23

Objectifier (Delegation Object)

n Reify a method by an objectn Delegate the behavior of the method to the objectn Vary the delegateen Factorizationn Varying behaviorn Used with: Bridge, Builder, Command, Iterator, Observer,

State, Strategy, Visitor.

24

Mediator

n Mediators encapsulate communicationn Partners can register with the mediator and do not know

with whom they talkn Communication can be varied dynamically

25

Mediator

#OLLEAGUE-EDIATORMediator

#ONCRETE-EDIATOR #ONCRETE#OLLEAGUE� #ONCRETE#OLLEAGUE�

!#OLLEAGUE

Mediator

!#ONCRETE-EDIATOR !#OLLEAGUE

Mediator

Typical Object Structure:

!#OLLEAGUE

Mediator

!#OLLEAGUE

Mediator

26

Example Mediator

n Many dependencies between parts of a windown Different widgets have different dependenciesn Encapsulate behavior in a mediator that mediates

between widgetsn Spare class factorizationn Widgets can be registered/deregistered dynamicallyn Flexible, but anonymous communication

27

Example Mediator

7IDGET$IALOGUE-EDIATORMediator

,IST"OX )NPUT&IELD

showDialog()CREATE7IDGETS�

WIDGET#HANGED�7IDGET

4EXT$IALOGUE-EDIATOR

createWidgets()widgetChanged(Widget)

select()

changed() Mediator.widgetChanged(this)

liste

field

Decoupling windows from text fields

28

Proxy

3UBJECT

OPERATION�

���

#LIENT

...realSubject.operation()

2EAL3UBJECT

operation()...

0ROXY

operation()...

realSubject

Hide the access to a real subject by a representant

29

Proxy

n References instead of valuesn Protocol proxy: counts references (reference-counting

garbage collectionn Indirection proxy: assembles ALL references to an object

to make it replaceablen Remote proxy: representant of a remote objectn Caching proxy: caches values which had been loaded

from the subjectn Remoten Loading lazy on demand

n Firewall: protection proxy

30

Adapter (Wrapper)

'OAL#LASS

OPERATION�

#LIENT !DAPTED#LASS

specificOperation()

!DAPTER

operation()

(Implementation)

specificOperation()

Adapts an interface to a clientMay use multiple inheritance, but need not

Can also be interface

31

Adapter (2)

'OAL

OPERATION�

#LIENT !DAPTIERTE#LASS

spezificOperation()

!DAPTER

operation()adaptedObject.spezificOperation()

Without Multiple Inheritance, but object adapter

adaptedObject

32

%XAMPLE��5SE�OF�AN�%XTERNAL�#LASS�,IBRARY

'RAFIC/BJECT

FRAMEW�

CREATE-ANIPULATOR�

$RAWING%DITOR

4EXT$ISPLAY

largeness()

return text.largeness()

,INIE

frame()createManipulator()

4EXT

frame()createManipulator()

return new TextManipulator

33

Compositum

Part/Whole hierarchies, e.g., nested graphic objects

A0ICTURE

A0ICTURE A2ECTANGLEA,INE

A0ICTURE A2ECTANGLEA,INE

common operations: draw(), move(), delete(), scale()

34

Structure Compositum

#OMPONENT

COMMON/PERATION�

add(Component)remove(Component)getType(int)

#OMPOSITUM

commonOperation()add(Component)remove(Component)getType(int)

,EAF

commonOperation()

#LIENT

childObjects

for all g in childObjects g.operation()

}Pseudo implementations

35

Compositum

n Class Compositum contains a container for the childobjects

n For iterations on hierarchies

36

Data Patterns

Memento SingletonFlyweight

37

Structure for Singleton

3INGLETON

static Singleton()private Singleton (first: bool)operation()getDaten()

static uniqueInstancedata

if uniqueInstance == null then uniqueInstance = new Singleton (true)return uniqueInstance

Assure one globally unique object of a class

38

Flyweight

n Set of objects is very largen State can be moved from object to external memory

(extrinsic state)n Identity of objects can be neglectedn Introduce flyweight objects

39

Structure for Flyweight

#ONCRETE&LYWEIGHT

operation(extrinsicState))

intrinsicState

3EPARATELY5SED

#ONCRETE&LYWEIGHT

operation(extrinsicState))

gesamtState

&LYWEIGHT&ACTORY

getFlyweight(key)

&LYWEIGHT

OPERATION�EXTRINSIC3TATE

#LIENT

if (Flyweighte[key] exists){ return Flyweight[key];} else { create new Flyweight; add to Flyweight; return it;}

Flyweighte

Representants with minimal space

40

Example Flyweight

Object modeling for characters in editor

Column

RowRow Row

e x a a m p l e

a b c d e f g h i j k l m

zn o p q r s t u v w x y

Set of Flyweights

41

Memento

-EMENTO

getState()setState()

State

#LIENT

restore(Memento m)createMemento()

State

#ONTAINERmemento

return new Memento(State) State = m.getState()

Extensionalize state of object

42

Example Memento

Breakpoints and Undo in editors, debuggers:

Rectangles should stay linkedIf they are moved.

Undo might be wrong if stateIs not sufficiently memorized

43

Coupling (Structural) Patterns

n Observern Bridgen (Adapter)n Facade

44

Observer (Publisher/Subscriber)

a=50%b=30%c=20%

7INDOW

a 30 30

10 20 10

b c

10

60 50 80

x y z

7INDOW7INDOW

a b c

Subject

Observer

Notify on change

Queries

45

Structure Observer

3UBJECT

REGISTER�/BSERVER

UNREGISTER�/BSERVER

NOTIFY�

/BSERVERObserver

#ONCRETES3UBJECT

getState()setState()

UPDATE��

#ONCRETER/BSERVER

update ()

ObserverState

for all b in Observer { b.update ()}

SubjectObserverState = Subject.getState()

return SubjectState

SubjectState

46

Sequence Diagram Observer

aConcreteSubject aConcreteObserver anotherConcreteObserver

SET3TATE()

NOTIFY()

UPDATE�N()

GET3TATE()

UPDATE�N()

GET3TATE()

REGISTER()

47

Observer

n Loose coupling in communicationn Observers decide what happens

n Dynamic change of communicationn Anonymous communicationn Multi-cast and broadcast communicationn Cascading effects (wavefront..)n If an abstraction has two aspects

n And one of them depends on the othern Reuse of aspects is possbile.

48

Observer Implementation

n If there is more than one subject: Send Subject asParameter of notify(Subject s).

n Push model: subject sends data in notify()n Pull model: observer fetches data itselfn Mediator between subjects and observer:

n May filter eventsn Stops cascaded propagations

49

Observer with ChangeManager

3UBJECT

REGISTER�/BSERVER

UNREGISTER�/BSERVER

NOTIFY�

/BSERVERObserver

#HANGE-ANAGER

REGISTER�3UBJECT�/BSERVER

UNREGISTER�3UBJECT�/BSERVER

NOTIFY�

Subject-Observer-mapping

UPDATE��3UBJECT

for all s in Subjects for all b in s.Observer b.update (s)

mark all observers to be updatedupdate all marked observers

manager.notify()

manager

Subjects

manager.register(this,b)

3IMPLE#HANGE-ANAGER

register(Subject,Observer)unregister(Subject,Observer)notify()

$!'#HANGE-ANAGER

register(Subject,Observer)unregister(Subject,Observer)notify()

50

Bridge (Handle/Body)

!BSTRACTION

operation()

#LIENT

)MPLEMENTATION

OPERATIONS)MP�

imp.operationsImp()

3PEZIALIZED!BSTRACTION

#ONCRETE)MPLEMENTATION"

operationsImp()

#ONCRETE)MPLEMENTATION!

operationsImp()

imp

Decouple an abstraction from

Its implementation

51

Example

Factorisation of class hierarchies with facet hierarchies

7INDOW

87INDOW 0-7INDOW

7INDOW

87INDOW 0-7INDOW )CON7INDOW

8)CON7INDOW 0-)CON7INDOW

52

Example

7INDOW

drawText()drawRectangle()

7INDOW)MP

imp.devicedrawLinie()imp.devicedrawLinie()imp.devicedrawLinie()imp.devicedrawLinie()

imp

DEVICEDRAW4EXT�

DEVICEDRAW,INIE�

87INDOW)MP

devicedrawText()devicedrawLinie()

0-7INDOW)MP

devicedrawText()devicedrawLine()

"RIDGE

)CON7INDOW

drawRahmen()

4RANSIENTES7INDOW

drawCloseButton()

XDrawLine() XDrawString()drawRectangle()drawRectangle()drawText()

53

Control flow Patterns

n Strategyn Visitor

n Iterator

n Pipelinen ChainOfResponsibility

54

Strategy

3TRATEGIE

ALGORITHM)NTERFACE�

#ONCRETE3TRATEGY!

algorithmInterface()

#ONCRETE3TRATEGY"

algorithmInterface()

#ONCRETE3TRATEGIE"

algorithmInterface()

#LIENT

contextInterface()

strategy

Define a family of algoriths

55

Example Strategy

&ORMATTER

FORMAT�

%INFACHER&ORMATTER

format()

+OMPOSITION

traverse()repair()

Formatter

4E8&ORMATTER

format()

!RRAY&ORMATTER

format()

Formatter.format()

Encapsulate formatting algorithms

Finding Patterns

57

How to find Patterns

n The process of looking for patterns to document is called PATTERNMINING.

n Patterns must not be ”new”, they grasp well-known solutions!n How do you know a pattern when you come across one? The

answer is you don't always know.n You may jot down the beginnings of some things you think are patterns,

but it may turn out that they aren’t patterns at all, or they are only piecesof patterns

n The best way to learn how to recognize and document useful patterns isby learning from others who have done it well!

n Pick up several books and articles which describe patterns (don’tchoose just one) and try and see if you can recognize all the necessarypattern elements.

n Read as much as you can, and try to learn from the masters.

58

How to write patterns

n ..is difficult!n Pattern writing involves abstraction (experience, experience, experience…)

n Avoid writing ABOUT patterns; just write patterns.

n Pick something you know about and then find multiple occurrences and/ordescriptions. Or conversely, MINE existing software for new possiblepatterns.

n Find out if other people have written similar patterns.

n Aim for quality, not quantity of patterns.

n Figure out why the pattern exists or applies.

n Pick a format for writing about it.

n Circulate it to others (for example, via web pages, patterns discussiongroups, or submissions to a mailing list) and receive comments.

n Continually iterate and refine.

59

Tooling

n IDEsn Together (Object International)

n Refactoring toolsn Refactorings are automated semantics-preserving

transformations which INTRODUCE�design patternsn COMPOST/Recoder recoder.sourceforge.netn XPTools AB Linköping

60

The End