+ All Categories
Home > Documents > Session 8: Design Patterns, Architectural Patterns

Session 8: Design Patterns, Architectural Patterns

Date post: 03-Feb-2017
Category:
Upload: nguyendien
View: 237 times
Download: 3 times
Share this document with a friend
127
1 Software Engineering G22.2440-001 Session 8 – Sub-Topic 1 Design Patterns, Architectural Patterns Dr. Jean-Claude Franchitti New York University Computer Science Department Courant Institute of Mathematical Sciences Design Patterns, Architectural Patterns
Transcript
Page 1: Session 8: Design Patterns, Architectural Patterns

1

1

Software EngineeringG22.2440-001

Session 8 – Sub-Topic 1Design Patterns, Architectural Patterns

Dr. Jean-Claude Franchitti

New York UniversityComputer Science Department

Courant Institute of Mathematical Sciences

Design Patterns, Architectural Patterns

Page 2: Session 8: Design Patterns, Architectural Patterns

2

3

Bibliography…« A System of Pattern » Bushmann et All« Design Patterns » Gamma et All« Concurrent Programming in Java » D. Lea.« Distributed Objects » Orfali et All« Applying UML and Patterns » Larman

4

Patterns…« Patterns help you build on the collective experience of skilled software engineers. »« They capture existing, well-provenexperience in software development andhelp to promote good design practice »« Every pattern deals with a specific, recurring problem in the design or implementation of a software system »« Patterns can be used to constructsoftware architectures with specificproperties… »

Page 3: Session 8: Design Patterns, Architectural Patterns

3

5

Becoming a Chess MasterFirst learn rules and physical requirements– e.g., names of pieces, legal movements, chess board

geometry and orientation, etc. Then learn principles– e.g., relative value of certain pieces, strategic value of

center squares, power of a threat, etc. However, to become a master of chess, one must study the games of other masters – These games contain patterns that must be understood,

memorized, and applied repeatedlyThere are hundreds of these patterns

6

Becoming a Software Designer Master

First learn the rules– e.g., the algorithms, data structures and languages of

software Then learn the principles– e.g., structured programming, modular programming,

object oriented programming, generic programming, etc. However, to truly master software design, one must study the designs of other masters – These designs contain patterns must be understood,

memorized, and applied repeatedlyThere are hundreds of these patterns

Page 4: Session 8: Design Patterns, Architectural Patterns

4

7

Software ArchitectureA software architecture is a description of thesubsystems and components of a software system and the relationships between them. Subsystems and components are typicallyspecified in different views to show therelevant functional and non-functionalproperties of a software system. The software system is an artifact. It is theresult of the software design activity.

8

ComponentA component is an encapsulated part of a software system. A component has an interface. Components serve as the building blocks for the structure of a system. At a programming-language level, components may be represented as modules, classes, objects or as a set ofrelated functions.

Page 5: Session 8: Design Patterns, Architectural Patterns

5

9

SubsystemsA subsystem is a set of collaboratingcomponents performing a given task. A subsystem is considered a separate entitywithin a software architecture. It performs its designated task by interactingwith other subsystems and components…

10

Architectural PatternsAn architectural Pattern expresses a fundamental structural organization schemafor software systems. It provides a set of predefined subsystems, their responsibilities, and includes rules and guidelines for organizing the relationships between them.

Page 6: Session 8: Design Patterns, Architectural Patterns

6

11

Design patternsA design pattern provides a scheme for refining the subsystems or components of a software system, or the relation shipsbetween them. It describes a commonly-recurring structure of communicatingcomponents that solves a general design problem within a particular context.

12

IdiomsAn Idiom is a low-level pattern specific to a programming language. An idiom describeshow to implement particular aspects of components or the relationships betweenthem using the features of the givenlanguage.

Page 7: Session 8: Design Patterns, Architectural Patterns

7

13

FrameworkA framework is a partially complete software (sub-) system that is intended to beinstantiated. It defines the architecture for a family of (sub-) systems and provides thebasic building blocks to create them. It alsodefines the places where adaptations for specific functionality should be made.

14

First ExampleA Dice GameA Player rolls 10x 2 dicesIf result = 7, score=score + 10 pointsAt the end, score of the player is registred in the highscore table.

Page 8: Session 8: Design Patterns, Architectural Patterns

8

15

menu

viewHighscore

Startturn=0

RollDice

turn++

Updatehighscore

Turn<10

[highscore] [start] [exit]

[true]

[false]

Activity Diagram

16

Analysis Diagram…

Playername : Stringscore : int = 0;

play()Player()

<<Actor>> DiefaceValue : int = 1

roll()Die()

1 21 2

Rolls

DiceGame

DiceGame()start()

1

1

1

1 Plays

1

1

1

1

Includes

HighScore

Highscore()add()

1

1

1

1

Scoring

Entryname:String : type = initvalscore:int : type = initval

Entry(name:String,score:int)()0..*1 0..*1

Page 9: Session 8: Design Patterns, Architectural Patterns

9

17

Design StageManage User Interface Manage Persistence of highscore in a file or in relational databaseRealize a layered architecture : Apply theLayer Architectural Pattern

18

LayerHelps structure an application that can bedecomposed into groups of subtasks in which each group of subtasks is at a particular level of abstraction.

Page 10: Session 8: Design Patterns, Architectural Patterns

10

19

Layer: examples

20

Layer :Structure

Page 11: Session 8: Design Patterns, Architectural Patterns

11

21

Layer: Structure

22

Layer and components…

Page 12: Session 8: Design Patterns, Architectural Patterns

12

23

Layers : VariantsRelaxed Layered System:– A layer « j » can use service of j-1, j-2…– A layer can be partially opaque

• Some service to layer j+1, others to all upperservices…

Layering through inheritance:– Lower layers are implemented as base classes– Higher level can override lower level…

24

Layers : Known UsesVirtual machines: JVM and binary code formatAPI : Layer that encapsulates lower layersInformation System– Presentation, Application logic, Domain Layer, Database

Windows NT (relaxed for: kernel and IO and hardware)– System services,– Resource management (Object manager, security monitor, process

manager, I/O manager, VM manager, LPC), – Kernel (exception handling, interrupt, multipro synchro, threads), – HAL (Hardware Abstraction Level)– Hardware

Page 13: Session 8: Design Patterns, Architectural Patterns

13

25

Layers: benefitsReuse of layersSupport for standardization (POSIX)Dependencies are kept localExchangeabilities :– Replacement of old implementation with Adapter

Pattern– Dynamic exchange with Bridge Pattern

26

Layers: LiabilitiesCascades of changing behaviorLower efficiencyUnnecessary work: functions of a layer called many times for one serviceDifficulty of establishing correct granularity of layers: Too few layers -> less benefits, too many layers -> complexity and overhead…

Page 14: Session 8: Design Patterns, Architectural Patterns

14

27

Applying Layer Architecture

Play View High Score

Fichier ou BDD

UI

Core

Persistence

28

Package decomposition

UI<<layer>>

Core<<layer>>

Persist<<layer>>

Util<<subsystem>>

Page 15: Session 8: Design Patterns, Architectural Patterns

15

29

Layer « core »Contain business logic classes…Adapt analysis classes for implementationUse of singleton Idiom…

30

Singleton (Idiom)Ensure a class only has one instance, andprovide a global point of access to it.

Page 16: Session 8: Design Patterns, Architectural Patterns

16

31

Singleton Structure

32

Core « Layer »:First diagram

Entryname:String : type = initvalscore:int : type = initval

Entry(name:String,score:int)()

HighScore$ hs : HighScore = null

Highscore()add()load()save()

1 0..*1 0..*

Playername : Stringscore : int = 0;

Player()display()

DiefaceValue : int = 1

roll()Die()display()

DiceGame$ dg = null

DiceGame()getInstance()start()

1

-player

1-dies

22

Singleton...

Playername : Stringscore : int = 0;

play()Player()

<<Actor>>

DiefaceValue : int = 1

roll()Die()

1 21 2

Rolls

DiceGame

DiceGame()start()

1

1

1

1Plays

1

1

1

1

Includes

Entryname:String : type = initvalscore:int : type = initval

Entry(name:String,score:int)()

HighScore

Highscore()add()

1

1

1

1

Scoring

0..*1 0..*1

Design Analysis

Page 17: Session 8: Design Patterns, Architectural Patterns

17

33

Package decomposition

UI<<layer>>

Core<<layer>>

Persist<<layer>>

Util<<subsystem>>

34

Observer

One-to-many dependency betweenobjects: change of one object willautomatically notify observers

Page 18: Session 8: Design Patterns, Architectural Patterns

18

35

Observer: ApplicabilityA change to one object requires changing an unknown set of other objectsObject should be able to notify other objectsthat may not be known at the beginning

36

Observer: Structure

Page 19: Session 8: Design Patterns, Architectural Patterns

19

37

Observer: ConsequencesAbstract coupling between subject andobserverSupport for broadcast communicationHard to maintain

38

Applying Observer Pattern Observable

changed : boolean = false

Observable()addObserver()deleteObserver()notifyObservers()notifyObservers()deleteObservers()setChanged()clearChanged()hasChanged()countObservers()

(from util)

DieView

DieView(die : Die)update(o : Observable, arg : Object) : void

PlayerView

PlayerView(player : Player)update(o : Observable, arg : Object) : void

Observer

update(o : Observable, arg : Object) : void

(from util)

<<Interface>>

0..*0..*

Player

name : Stringscore : int = 0;

Player()display()

(from Core)

Die

faceValue : int = 1

roll()Die()display()

(from Core)

Page 20: Session 8: Design Patterns, Architectural Patterns

20

39

Observer ViewObserver

update(o : Observable, arg : Object) : void

(from uti l)

<<Interface>>

DieView

DieView(die : Die)update(o : Observable, arg : Object) : void

PlayerView

PlayerView(player : Player)update(o : Observable, arg : Object) : void

40

Views are graphical objects

DieView

DieView(die : Die)update(o : Observable, arg : Object) : void

PlayerView

PlayerView(player : Player)update(o : Observable, arg : Object) : void

Observable

changed : boolean = false

Observable()addObserver()deleteObserver()notifyObservers()notifyObservers()deleteObservers()setChanged()clearChanged()hasChanged()countObservers()

(from util)

Observer

update(o : Observable, arg : Object) : void

(from util)

<<Interface>>

0..*0..*

Player

name : Stringscore : int = 0;

Player()display()

(from Core)

Die

faceValue : int = 1

roll()Die()display()setValue()

(from Core)

Panel

Panel()Panel()constructComponentName()addNotify()

(from awt)

Page 21: Session 8: Design Patterns, Architectural Patterns

21

41

Setting up Observer : RollForm : Die : DieView :

Playe : PlayerView

1: display( )2: PlayerView(Player)

4: return component

5: display()6: DieView(Die)

8: return component

3: addObserver(Observer)

7: addObserver(Observer)

42

Observer : Change Propagation: Die : Randomizer : DieView

1: getValue( )

2: setValue(int)

3: notifyObservers( )

4: update(Observable, Object)5: getState()

3

: JLabel

6: setText(3)

Page 22: Session 8: Design Patterns, Architectural Patterns

22

43

Layered Architecture...

DiefaceValue : int = 1

roll()Die()display()setValue()

Playername : Stringscore : int = 0;

Player()display()

Observer(from util)

<<Interface>>Observable(from util)

0..*0..*

Displayable<<Interface>>

PlayerView

PlayerView()update()

(from UI)

RollForm

roll_action()cancel_action()RollForm()

(from UI)

1

+thePlayerView

1DieView

DieView()update()

(from UI) +theDieView

22

UI

Core

Decoupling classes

and interfaces

44

Package decomposition

UI<<layer>>

Core<<layer>>

Persist<<layer>>

Util<<subsystem>>

Page 23: Session 8: Design Patterns, Architectural Patterns

23

45

Pattern Factory MethodIntent– Define an interface for creating an object, but let

sub-classes decide which class to instantiate– let a class defer instantiation to subclasses– Also known as Virtual Constructor

46

Factory MethodApplicability : Use when– a class cannot anticipate the class of objects it

must create– a class wants its subclasses to specify the

objects it creates– classes delegate responsibility to one of several

helper subclasses, and you want to localize theknowledge of which helper subclass to delegate.

Page 24: Session 8: Design Patterns, Architectural Patterns

24

47

Structure

Produit

ProduitConcret

Facteur

Fabrication()UneOperation()

FacteurConcret

Fabrication()

produit=Fabrication()

return new ProduitConcret()

48

Factory methodConsequences– Provide hooks for subclasses– connects parallel class hierarchies

Known uses– MacApp, ET++– ClassView in smalltalk80 MVC (controller

creation)– Orbix ORB for generating PROXY object

Page 25: Session 8: Design Patterns, Architectural Patterns

25

49

« Persist » LayerPersistence technical classesEnsure independence of Core/Persist– Be able to switch « persistent engine »

For example:– Persistence via « Serialization »– Persistence via a relational database (JDBC).

50

Applying FactoryHighScore

$ hs : HighScore = null

Highscore()add()load()save()

(from Core)

PersistKit

makeKit()

JdbcKit

makeKit()

SrKit

makeKit()

HighScoreJDBC

Highscore()load()save()

HighScoreSr$ filename : String = "/tmp/high.score"

Highscore()load()save()

Abstract produc

Abstract Factory

Concrete product

Concrete Factory

Page 26: Session 8: Design Patterns, Architectural Patterns

26

51

: RealPlayer : SrK it : HighScoreSr : DiceGame

2: getInstance( )

3: DiceGame( )

1: SrKit( )

4: makeKit( ) 5: HighScoreSr( )

A ttention!DiceGame voit SrK it comme un PersistKit et HighScoreSr comme un HighScore

6: load( )

7: quit( ) 8: getInstance( )

9: save( )

Seul le Realplayer sait qu'il utilise un SrK it ! DiceGame non !

Applying Factory

52

Summary1 Architectural pattern : Layer2 Design Patterns : Observer, Factory1 Idiom : SingletonPb:– Combining pattern to combine their forces…

Page 27: Session 8: Design Patterns, Architectural Patterns

27

53

54

Bank example…A basic bank system:– 1 bank, n Account. – Each account belong to 1 client.– Each account is credited by an amount a money.

Bank functions– Withdrawal on an account, Credit an account,

Transfer money from one account to another…

Page 28: Session 8: Design Patterns, Architectural Patterns

28

55

Naive solutionBank

addAccount(S tring name, int amount) : Accountwithdrawal(int ida, int amount) : voiddeposit(int ida, int amout) : vo idtransfer(int ida1, int ida2, int amount) : vo idgetAccount(int ida) : Account

Accountint amountint ida

withdraw(int a)deposit(int a)Account(int ida)

CustomerString name;int idc

Client(String name, int idc)ida : int

11..n 1ida : int

1 ..n

ida : int

1

0..n

1

ida : int

0..n

1

0..n

idc : intidc : int

1

0..n

56

Naive Solution1 : A c c o u n t : c li e n t : B a n k 2 : A c c o u n t

tr a n s fe r ( 1 ,2 ,1 0 0 )

w i th d r a w a l (1 ,1 0 0 )

w i th d r a w ( 1 0 0 )

d e p o s i t( 2 ,1 0 0 )

d e p o s i t ( 1 0 0 )

g e tA c c o un t( 1 )

g e tA c c o un t( 2 )

Page 29: Session 8: Design Patterns, Architectural Patterns

29

57

Applying Command Pattern…Encapsulate a request as an object, therebyletting you parameterize clients with differentrequests, queue or log requests, and support undoable operations.

58

Command Example

Page 30: Session 8: Design Patterns, Architectural Patterns

30

59

Command Example

60

Command Structure

Page 31: Session 8: Design Patterns, Architectural Patterns

31

61

Command Structure

62

Command ConsequencesCommand decouples the object thatinvokes the operation from the one thatknows how to perform it. Commands are first-class objects. Theycan be manipulated and extended like anyother object. It's easy to add new Commands, because you don't have to change existing classes.

Page 32: Session 8: Design Patterns, Architectural Patterns

32

63

Applying Command Pattern

Accountint amountint ida

withdraw(a : int)deposit(a : int)

CustomerString name;int idc

Client(String name, int idc)

ida : int11..n 1

ida : int1..n

Withdrawalida : intamount : int

do() : voidundo:void()

Commandb : banque

do() : voidundo() : voidCommand(Bank b)

Bank

getAccount(int ida) : AccountExecute(cmd : Command) : void

ida : int

1

0..n

1

ida : int

0..n

idc : int1

0..n

1idc : int

0..n

+receiver

Depositida : intamount : int

do() : voidundo: void()

Transferida1 : intida2 : intamount : int

do() : voidundo:void()opname()Transfer(ida1 : int, ida2 : int, int a, Bank b)

64

Applying Command Pattern : client t : Transfer : Bank 1 : Account 2 : Account

Transfer(1,2,100 )

Execute(t )

do( )

getAccount( 1)

withdraw( 100)

getAccount( 2)

deposit( )

Page 33: Session 8: Design Patterns, Architectural Patterns

33

65

Composite PatternCompose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects andcompositions of objects uniformly.

66

Composite Example

Page 34: Session 8: Design Patterns, Architectural Patterns

34

67

Composite Example

68

Composite Structure

Page 35: Session 8: Design Patterns, Architectural Patterns

35

69

Applying Composite on Command

70

Applying Composite

Accountint amountint ida

withdraw(a : int)deposit(a : int)

CustomerString name;int idc

Client(String name, int idc)

ida : int11..n 1

ida : int1..n

Withdrawalida : intamount : int

do() : voidundo:void()Withdrawal(b : Bank, ida : int, amount : int)

Bank

getAccount(int ida) : AccountExecute(cmd : Command) : void

ida : int

1

0..n

1

ida : int

0..n

idc : int1

0..n

1idc : int

0..n

Depositida : intamount : int

do() : voidundo: void()Deposit(b : Bank, ida : int, amount : int)

Macrocom

add(Command cmd)remove(Command cmd)do()undo()Macrocom(b : Bank)

Commandb : banque

do() : voidundo() : voidCommand(Bank b)

+receiver

0..n0..n

Page 36: Session 8: Design Patterns, Architectural Patterns

36

71

: client w : Withdrawal d : Deposit m : Macrocom : Bank 1 : Account 2 : Account

Withdrawal(b, 1,100 )

Deposit(b,2,100 )

Macrocom(b )

add( w)

add(d )

Execute(m )

do( )do( )getAccount( 1)

withdraw( 100)

do( )

getAccount( 2)

deposit( 100)

72

Applying Singleton

Accountint amountint ida

withdraw(a : int)deposit(a : int)

CustomerString name;int idc

Client(String name, int idc)

ida : int11..n 1

ida : int1..n

Withdrawalida : intamount : int

do() : voidundo:void()Withdrawal(ida : int, amount : int)

Bankinstance : Bank

getAccount(int ida) : AccountExecute(cmd : Command) : voidgetInstance() : Bank

ida : int

1

0..n

1

ida : int

0..n

idc : int1

0..n

1idc : int

0..n

Depositida : intamount : int

do() : voidundo: void()Deposit(ida : int, amount : int)

Macrocom

add(Command cmd)remove(Command cmd)do()undo()Macrocom()

Command

do() : voidundo() : void

0..n0..n

do () { Bank b=Bank.getInstance(); ...}

Page 37: Session 8: Design Patterns, Architectural Patterns

37

73

And So on…Storing state : Memento PatternObserving Account : Observer PatternVisiting all object graph : Visitor PatternRemote access : Proxy pattern…

74

Proxy PatternProvide a surrogate or placeholder for another object to control access to it.

Page 38: Session 8: Design Patterns, Architectural Patterns

38

75

Proxy Example

76

Proxy Structure

Page 39: Session 8: Design Patterns, Architectural Patterns

39

77

Proxy benefitsremote proxy can hide the fact that an object resides in a different address space. A virtual proxy can perform optimizationssuch as creating an object on demand. Both protection proxies and smart references allow additional housekeepingtasks when an object is accessed.

78

AccountCreate

sum : int

AccountCreate(arg0 : String, arg1 : int)execute() : voidunexecute() : voidtoString() : String

(from remotecommand)

AccountDeposit

sum : int

AccountDeposit(arg0 : String, arg1 : int)execute() : voidunexecute() : void

(from remotecommand)

AccountViewer

AccountViewer(arg0 : String)update(arg0 : Object) : void

(from remotecommand)

AccountWithdrawal

sum : int

AccountWithdrawal(arg0 : String, arg1 : int)execute() : voidunexecute() : void

(from remotecommand) BankAccount

amount : int

BankAccount(arg0 : String, arg1 : int)name() : Stringamount() : intamount(arg0 : int) : voidtoString() : String

(from remotecommand)

RemoteObservable

changed : boolean

addObserver(arg0 : RemoteObserver) : voidremoveObserver(arg0 : RemoteObserver) : voidsetChanged() : voidnotifyObservers() : voidnotifyObservers(arg0 : Object) : voidRemoteObservable()

(from remotecommand)

BankBase

instance() : BankBaseaddAccount(arg0 : BankAccount) : voidgetAccount(arg0 : String) : BankAccountremoveAccount(arg0 : String) : voidtoString() : StringBankBase()

(from remotecommand)

$bb

BankServer

BankServer()execute(arg0 : Command) : voidmain(arg0 : String[]) : void

(from remotecommand)

BankServerI

execute(arg0 : Command) : void

(from remotecommand)

<<Interface>>

RemoteObserver

update(arg0 : Object) : void

(from remotecommand)

<<Interface>>

RegisterObserver

RegisterObserver(arg0 : String, arg1 : RemoteObserver)execute() : voidunexecute() : void

(from remotecommand)

ro

Command

execute() : voidunexecute() : voidCommand()

(from remotecommand)

MacroCommand

execute() : voidunexecute() : voidadd(arg0 : Command) : voidMacroCommand()

(from remotecommand)

Page 40: Session 8: Design Patterns, Architectural Patterns

40

79

Adapter PatternConvert the interface of a class into anotherinterface clients expect. Adapter lets classes work together that couldn't otherwisebecause of incompatible interfaces.

80

Adapter Example

Page 41: Session 8: Design Patterns, Architectural Patterns

41

81

Adapter Structure

82

Visitor PatternRepresent an operation to be performed on the elements of an object structure. Visitorlets you define a new operation withoutchanging the classes of the elements on which it operates.

Page 42: Session 8: Design Patterns, Architectural Patterns

42

83

Visitor example

84

Visitor example

Page 43: Session 8: Design Patterns, Architectural Patterns

43

85

Visitor applicabilitymany distinct and unrelated operations needto be performed on objects in an objectstructure, and you want to avoid "polluting" their classes with these operations

86

Visitor Structure

Page 44: Session 8: Design Patterns, Architectural Patterns

44

87

Visitor Structure

88

Visitor ConsequencesVisitor makes adding new operations easyA visitor gathers related operations andseparates unrelated onesAdding new Concrete Element classes ishardVisiting across class hierarchiesAccumulating state.Breaking encapsulation

Page 45: Session 8: Design Patterns, Architectural Patterns

45

89

Chain of responsibilityAvoid coupling the sender of a request to itsreceiver by giving more than one object a chance to handle the request. Chain thereceiving objects and pass the request alongthe chain until an object handles it.

90

Page 46: Session 8: Design Patterns, Architectural Patterns

46

91

Chain of Responsibility

92

Chain of Responsibility

Page 47: Session 8: Design Patterns, Architectural Patterns

47

93

ParticipantsHandler (HelpHandler) – defines an interface for handling requests. – (optional) implements the successor link. ConcreteHandler (PrintButton, PrintDialog) – handles requests it is responsible for. – can access its successor. – if the ConcreteHandler can handle the request, it does

so; otherwise it forwards the request to its successor. Client– initiates the request to a ConcreteHandler object on the

chain.

94

Example…Awt 1.0

Page 48: Session 8: Design Patterns, Architectural Patterns

48

95

StrategyDefine a family of algorithms, encapsulateeach one, and make them interchangeable. Strategy lets the algorithm varyindependently from clients that use it.

96

Strategy…

Page 49: Session 8: Design Patterns, Architectural Patterns

49

97

Strategy

98

ParticipantsStrategy (Compositor) – declares an interface common to all supported

algorithms. Context uses this interface to call thealgorithm defined by a ConcreteStrategy.

ConcreteStrategy (SimpleCompositor, TeXCompositor, ArrayCompositor) – implements the algorithm using the Strategy interface. Context (Composition) – is configured with a ConcreteStrategy object. – maintains a reference to a Strategy object. – may define an interface that lets Strategy access its

data.

Page 50: Session 8: Design Patterns, Architectural Patterns

50

99

Strategy…

B u tto n(fro m a w t )

B o rd e rL a y o u t( fro m a w t )

C o m p o n e n t( fro m a w t )

G r i d L a y o u t( fro m a w t )

L a y o u tM a n a g e r2( fro m a w t )

< < In te r fa c e > >

C o n ta i n e r( fro m a w t )

c o m p o n e n t[ ]

L a y o u tM a n a g e r( fro m a w t )

< < In te r fa c e > >la y o u tM g r

100

StateAllow an object to alter its behavior when itsinternal state changes. The object willappear to change its class.

Page 51: Session 8: Design Patterns, Architectural Patterns

51

101

Example

102

Structure

Page 52: Session 8: Design Patterns, Architectural Patterns

52

103

Consequences1. It localizes state-specific behavior and

partitions behavior for different states2. It makes state transitions explicit3. State objects can be shared

104

DecoratorAttach additional responsibilities to an objectdynamically. Decorators provide a flexible alternative to subclassing for extendingfunctionality.

Page 53: Session 8: Design Patterns, Architectural Patterns

53

105

Example

106

Example

Page 54: Session 8: Design Patterns, Architectural Patterns

54

107

Example

108

Structure

Page 55: Session 8: Design Patterns, Architectural Patterns

55

109

Applicabilityto add responsibilities to individual objectsdynamically and transparently, that is, without affecting other objects. for responsibilities that can be withdrawnwhen extension by subclassing is impractical

110

Consequences1. More flexibility than static inheritance2. Avoids feature-laden classes high up in the

hierarchy3. A decorator and its component aren't

identical4. Lots of little objects

Page 56: Session 8: Design Patterns, Architectural Patterns

56

111

FileInputStream

FileInputStream(name : String)FileInputStream(file : File)FileInputStream(fdObj : FileDescriptor)open(name : String) : voidread() : intreadBytes(b[] : byte, off : int, len : int) : intread(b[] : byte) : intread(b[] : byte, off : int, len : int) : intskip(n : long) : longavailable() : intclose() : voidgetFD() : FileDescriptorinitIDs() : voidfinalize() : void

(from io)

BufferedInputStream

defaultBufferSize : int = 2048buf[] : bytecount : intpos : intmarkpos : int = - 1marklimit : int

ensureOpen()BufferedInputStream()BufferedInputStream()fill()read()read1()read()skip()available()mark()reset()markSupported()close()

(from io)PushbackInputStream

buf[] : bytepos : int

ensureOpen()PushbackInputStream()PushbackInputStream()read()read()unread()unread()unread()available()skip()markSupported()close()

(from io)LineNumberInputStream

pushBack : int = - 1lineNumber : intmarkLineNumber : intmarkPushBack : int = - 1

LineNumberInputStream()read()read()skip()setLineNumber()getLineNumber()available()mark()reset()

(from io)

InputStream

SKIP_BUFFER_SIZE : int = 2048skipBuffer[] : byte

read()read()read()skip()available()close()mark()reset()markSupported()

(from io)

FilterInputStream

FilterInputStream()read()read()read()skip()available()close()mark()reset()markSupported()

(from io)

#in

112

BridgeDecouple an abstraction from itsimplementation so that the two can varyindependently.

Page 57: Session 8: Design Patterns, Architectural Patterns

57

113

Bridge

114

Bridge

Page 58: Session 8: Design Patterns, Architectural Patterns

58

115

Bridge Structure…

116

Bridge1. Decoupling interface and implementation2. Improved extensibility3. Hiding implementation details from clients

Page 59: Session 8: Design Patterns, Architectural Patterns

59

117

ExampleUIManager

ListUI LabelUI

BasicLookAndFeel BasicLabelUI

JComponentComponentUI

createUI()installUI()paint()

#ui

MetalLookAndFeel

LAFState

LookAndFeel

getName()installColors()

lookAndFeel

MultiLookAndFeel MultiListUIMultiLabelUI

MetalLabelUI

BasicListUI

JList

#list

JLabel

118

Page 60: Session 8: Design Patterns, Architectural Patterns

60

119

BuilderSeparate the construction of a complexobject from its representation so that thesame construction process can createdifferent representations.

120

Builder

Page 61: Session 8: Design Patterns, Architectural Patterns

61

121

Builder Structure…

122

Builder

Page 62: Session 8: Design Patterns, Architectural Patterns

62

123

Builder Consequences1. It lets you vary a product's internal

representation2. It isolates code for construction and

representation3. It gives you finer control over the

construction process

124

FlyWeightUse sharing to support large numbers of fine-grained objects efficiently.

Page 63: Session 8: Design Patterns, Architectural Patterns

63

125

FlyWeight

126

Flyweight: Structure

Page 64: Session 8: Design Patterns, Architectural Patterns

64

127

Flyweight example

128

Flyweight: Instances

Page 65: Session 8: Design Patterns, Architectural Patterns

65

129

Flyweight: ApplicabilityEtat intrinsèque/extrinsèque…Les états extrinsèques peuvent être calculés…

130

Flyweight (il a rien compris… ☺)

Page 66: Session 8: Design Patterns, Architectural Patterns

66

131

IteratorProvide a way to access the elements of an aggregate object sequentially withoutexposing its underlying representation

132

Iterator

Page 67: Session 8: Design Patterns, Architectural Patterns

67

133

Iterator example:

134

Example

Page 68: Session 8: Design Patterns, Architectural Patterns

68

135

MementoWithout violating encapsulation, capture andexternalize an object's internal state so thatthe object can be restored to this state later.

136

Memento Structure…

Page 69: Session 8: Design Patterns, Architectural Patterns

69

137

Memento…1. Preserving encapsulation boundaries2. It simplifies Originator3. Using mementos might be expensive.4. Defining narrow and wide interfaces5. Hidden costs in caring for mementos

138

Case Study

Page 70: Session 8: Design Patterns, Architectural Patterns

70

139

Design problems…Document structure. The choice of internal representationfor the document affects nearly every aspect of Lexi's design. All editing, formatting, displaying, and textualanalysis will require traversing the representation. Theway we organize this information will impact the design of the rest of the application. Formatting. How does Lexi actually arrange text andgraphics into lines and columns? What objects are responsible for carrying out different formatting policies? How do these policies interact with the document's internal representation?

140

Design problems…Embellishing the user interface. Lexi's user interface includes scroll bars, borders, and drop shadows that embellish the WYSIWYG document interface. Such embellishments are likely to change as Lexi's user interface evolves. Hence it's important to be able to add and removeembellishments easily without affecting the rest of the application. Supporting multiple look-and-feel standards. Lexishould adapt easily to different look-and-feelstandards such as Motif and PresentationManager (PM) without major modification.

Page 71: Session 8: Design Patterns, Architectural Patterns

71

141

Design problems…Embellishing the user interface. Lexi's user interface includes scroll bars, borders, and drop shadows that embellish the WYSIWYG document interface. Such embellishments are likely to change as Lexi's user interface evolves. Hence it's important to be able to add and removeembellishments easily without affecting the rest of the application. Supporting multiple look-and-feel standards. Lexishould adapt easily to different look-and-feelstandards such as Motif and PresentationManager (PM) without major modification.

142

Design problems…Spelling checking and hyphenation. How does Lexi support analytical operationssuch as checking for misspelled words anddetermining hyphenation points? How canwe minimize the number of classes wehave to modify to add a new analyticaloperation?

Page 72: Session 8: Design Patterns, Architectural Patterns

72

143

144

Page 73: Session 8: Design Patterns, Architectural Patterns

73

145

146

Page 74: Session 8: Design Patterns, Architectural Patterns

74

147

148

Page 75: Session 8: Design Patterns, Architectural Patterns

75

149

150

Page 76: Session 8: Design Patterns, Architectural Patterns

76

151

152

Page 77: Session 8: Design Patterns, Architectural Patterns

77

153

154

Page 78: Session 8: Design Patterns, Architectural Patterns

78

155

156

Page 79: Session 8: Design Patterns, Architectural Patterns

79

157

158

Page 80: Session 8: Design Patterns, Architectural Patterns

80

159

Summary (C. Alexander)

It is possible to create building architectures by stringing together patterns in a rather looseway. A building made like this, is an assemblyof patterns. It is not dense. It is not profound. But it is also possible to put patterns together in such way that many patterns overlap in thesame physical space: the building is verydense; it has many meanings captured in a small space; and through this density, itbecomes profound.

160

Architectural Patterns…From MUD to Structure…– Layers, Pipe and Filters, Blackboard

Distributed Systems…– Broker, Pipe and Filters, Microkernel

Interactive Systems…– MVC, PAC

Adaptable Systems…– Microkernel, Reflection…

Page 81: Session 8: Design Patterns, Architectural Patterns

81

161

Layerhelps structure application that can bedecomposed into groups of subtasks in which each group of subtasks is at a particular level of abstraction.

162

Layer: examples

Page 82: Session 8: Design Patterns, Architectural Patterns

82

163

Layer :Structure

164

Layer: Structure

Page 83: Session 8: Design Patterns, Architectural Patterns

83

165

Layer and components…

166

Layer and Facade DP…

Page 84: Session 8: Design Patterns, Architectural Patterns

84

167

Layer and Facade DP

168

Layers : VariantsRelaxed Layered System:– A layer « j » can use service of j-1, j-2…– A layer can be partially opaque

• Some service to layer j+1, others to all upperservices…

Layering through inheritance:– Lower layers are implemented as base classes– Higher level can override lower level…

Page 85: Session 8: Design Patterns, Architectural Patterns

85

169

Layers : Known UsesVirtual machines: JVM and binary code formatAPI : Layer that encapsulates lower layersInformation System– Presentation, Application logic, Domain Layer, Database

Windows NT (relaxed for: kernel and IO and hardware)– System services,– Resource management (Object manager, security monitor, process

manager, I/O manager, VM manager, LPC), – Kernel (exception handling, interrupt, multipro synchro, threads), – HAL (Hardware Abstraction Level)– Hardware

170

Layers: benefitsReuse of layersSupport for standardization (POSIX)Dependencies are kept localExchangeabilities :– Replacement of old implementation with Adapter

Pattern– Dynamic exchange with Bridge Pattern

Page 86: Session 8: Design Patterns, Architectural Patterns

86

171

Layers: LiabilitiesCascades of changing behaviorLower efficiencyUnnecessary work: functions of a layer called many times for one serviceDifficulty of establishing correct granularity of layers: Too few layers -> less benefits, too many layers -> complexity and overhead…

172

Pipes and FiltersProvides a structure for systems thatprocess a stream of Data. Each processingstep is encapsulated in a filter component. Data is passed through pipes betweenadjacent filters.Recombining filters allows the building offamilies of related systems.

Page 87: Session 8: Design Patterns, Architectural Patterns

87

173

Pipes and Filters: Example

174

Pipes and Filters: Structure

Page 88: Session 8: Design Patterns, Architectural Patterns

88

175

Pipes and Filters

176

Pipes and Filters: push pipeline

Page 89: Session 8: Design Patterns, Architectural Patterns

89

177

Pipes and Filters: pull pipeline

178

Pipes and Filters: push-pull pipeline

Page 90: Session 8: Design Patterns, Architectural Patterns

90

179

Pipes and Filters : Threaded Filters

180

Pipes and Filters: Known UsesUnix CMS Pipelines (extension IBM mainframes)LASSPTools (Numerical Analysis)– Graphical input devices (knobs or sliders)– Filters for numerical analysis and data extraction– Data sinks to produce animation from numerical

data streams…Khoros : Image recognition…WEB !! Servlet !!

Page 91: Session 8: Design Patterns, Architectural Patterns

91

181

Pipes and Filters BenefitsNo intermediate file necessary (but possible)Flexibility by filter exchangeFlexibility by recombinationReuse of filter componentsRapid prototyping of pipelineEfficiency by parallel processing

182

Pipes and Filters LiabilitiesSharing state information is expensive or inflexibleEfficiency gain by parallel processing is oftenan illusion – Cost of data transfer, filters that consume all

data before one output, context switch on one computer, synchronization of filters via pipes

Data transformation overheadError Handling

Page 92: Session 8: Design Patterns, Architectural Patterns

92

183

[Sun Developpers]

184

Page 93: Session 8: Design Patterns, Architectural Patterns

93

185

BlackboardThe Blackboard architectural pattern isuseful for problems for which no deterministic solution strategies are known. Several specialized subsystems assemble their knowledge to build a possibly partial or approximate solution.

186

Blackboard Example

Page 94: Session 8: Design Patterns, Architectural Patterns

94

187

Blackboard Structure

188

Blackboard Structure

Page 95: Session 8: Design Patterns, Architectural Patterns

95

189

Blackboard Structure

190

Blackboard VariantsProduction System (OPS Language)– Blackboard : working memory– Knowledge source: Condition-action rules– Control: conflict resolution module.

Repository: – blackboard: Data, – Application program: knowledge source.– Control: user input, external program

Page 96: Session 8: Design Patterns, Architectural Patterns

96

191

Blackboard known usesHEARSAY-II: Speech recognitionHASP/SIAP: detect enemy submarineCrysalis: infer three-dimensional structure of protein molecule from X-Ray diffraction Data.Tricero: Aircraft activities. Extend blackboardto distributed computing

192

Blackboard benefitsExperimentation: different algo, differentcontrol heuristicsChangeability and maintainability: separationdata/control.Reusable knowledge sourceSupport for Fault tolerance and robustness: Tolerance of noisy data…

Page 97: Session 8: Design Patterns, Architectural Patterns

97

193

Blackboard LiabilitiesDifficulty of testing: no deterministic algoNo good solution is guaranteed.Difficulty of establishing a good control strategyLow efficiency: (rejecting wrong hypothesis)High development effort : trial-and-errorprogrammingNo support for parallelism

194

Page 98: Session 8: Design Patterns, Architectural Patterns

98

195

BrokerUsed to structure distributed software systems with decoupled components thatinteract by remote service invocation. A broker component is responsible for coordinating communication, such as forwarding request, as well as for transmitting result and exception.

196

Broker example

Page 99: Session 8: Design Patterns, Architectural Patterns

99

197

Broker structure

198

Broker Structure

Page 100: Session 8: Design Patterns, Architectural Patterns

100

199

Broker Structure

200

Broker Structure

Page 101: Session 8: Design Patterns, Architectural Patterns

101

201

Broker Structure

202

Broker VariantsDirect Communication Broker System:– Direct link to server

Message Passing Broker System– Focus on transmission of data. Type of the

message determine the behavior of the broker…Trader System : – service identifiers are used to access server

functionality. Request can be forwarded to more than one server…

Callback broker system: event driven…

Page 102: Session 8: Design Patterns, Architectural Patterns

102

203

Known UsesCORBAIBM SOM/DSOMMicrosoft Ole 2.xWWWATM-P: Message passing broker. Telecommunication switching system basedon ATM.

204

Broker benefitsLocation transparencyChangeability and extensibility of componentsPortability of a broker system (Layered)Interoperability between brokers (bridge)Reusability (of services)

Page 103: Session 8: Design Patterns, Architectural Patterns

103

205

Broker LiabilitiesRestricted efficiency (indirection layer)Lower Fault tolerance: fault a broker or a server… replication of components…Testability:– Of components (benefits)– Of application (liabilities)

206

Model-View-Contoler (MVC)The model contains the core functionalityand data?Views display information to the user.Controllers handle user input.A change propagation mechanism ensureconsistency between user interface and themodel.

Page 104: Session 8: Design Patterns, Architectural Patterns

104

207

MVC

208

MVC Structure

Page 105: Session 8: Design Patterns, Architectural Patterns

105

209

MVC Structure

210

MVC Structure

Page 106: Session 8: Design Patterns, Architectural Patterns

106

211

MVC Known UsesSmalltalkMFCET++: application FrameworkJava/Swing

212

MVC benefitsMultiple views of the same modelSynchronized views: change propagationPluggable views and controllersExchangeability of ‘look and feel’Framework potential

Page 107: Session 8: Design Patterns, Architectural Patterns

107

213

MVC LiabilitiesIncreased complexityPotential for excessive number of updatesIntimate connection between view andcontrollerClose coupling of views and controllers to a modelInefficiency of data access in viewInevitability of change to view and controllerwhen portingDifficulty of using MVC with modern user-interface tools

214

Presentation-Abstraction-ControlPAC define a hierarchy of cooperatingagents.Each agent consists of three components: presentation, abstraction, control.Separates human computer interaction fromits functional core and its communication with other agents…

Page 108: Session 8: Design Patterns, Architectural Patterns

108

215

PAC Example

216

PAC Example

Page 109: Session 8: Design Patterns, Architectural Patterns

109

217

PAC Structure

218

Top Level PACAbstraction : Global Data model Presentation : Some Graphical elementsControl:– Allow sub-agent to access abstraction– Manage hierarchy of PAC component – Manage info about interaction (log, check

applicability of triggered application…

Page 110: Session 8: Design Patterns, Architectural Patterns

110

219

220

PAC Structure

Page 111: Session 8: Design Patterns, Architectural Patterns

111

221

PAC Structure

222

PAC Structure

Page 112: Session 8: Design Patterns, Architectural Patterns

112

223

PAC Structure

224

PAC Known UsesNetwork Trafic Management (TS93)– Gathering traffic data– Threshold checking and generation exceptions– Logging and routing of network exception– Vizualisation of traffic flow and network exceptions– Displaying various user-configurable views of the whole

network– Statistical evaluation of traffic data– Access to historic traffic data– System administration and configuration

Page 113: Session 8: Design Patterns, Architectural Patterns

113

225

PAC BenefitsSeparation of concerns: Agent and inside an agentSupport for change and extensionSupport for multi-tasking: each PAC agent can run its own thread on a differentcomputer…

226

PAC LiabilitiesIncreased system complexity: Coordination of agents…Complex control component: coordonateaction inside agent and with other agents…Efficiency : data are propagated throught thetree…Applicability : Not a graphic editor whereeach object is a PAC agent…

Page 114: Session 8: Design Patterns, Architectural Patterns

114

227

MicrokernelApplies to software systems that be able to adapt to changing system requirements.It separates a minimal functional core fromextended functionality and customer specificparts.The Microkernel also serves as a socket for plugging in these extensions andcoordinating their collaboration.

228

Microkernel

Page 115: Session 8: Design Patterns, Architectural Patterns

115

229

Microkernel Architecture

230

Microkernel Architecture

Page 116: Session 8: Design Patterns, Architectural Patterns

116

231

Microkernel Architecture

232

Microkernel Structure

Page 117: Session 8: Design Patterns, Architectural Patterns

117

233

Microkernel Structure

234

Microkernel variantsMicrokernel system with indirect Client-Server connections. MK establish channel of communication between client and externalservers.

Page 118: Session 8: Design Patterns, Architectural Patterns

118

235

Microkernel known UsesMach (92): Emulate other operating system (NeXTSTEP)Amoeba (92): – Kernel: process, threads system memory,

communication, IO– Services not in the kernel are internal servers..

236

Known usesChorusWINDOWS NT: – External servers: OS/2.1.X, posix server and

win32 serverMKDE: Microkernel Databank Engine– External server : Data model of SQL database

Page 119: Session 8: Design Patterns, Architectural Patterns

119

237

Microkernel BenefitsPortability : no need to port externalservers…Flexibility and extensibilitySeparation of policy and mechanism:– Mechanism in kernel, policy in external servers

ScalabilityReliability: Distributed Microkernel… :-/Transparency : Microkernel ~ broker…

238

Microkernel LiabilitiesPerformanceComplexity of design and implementation.– Basic functionalities of the micro-kernel ??– Separation mechanism/policy => deep

knowledge of domain.

Page 120: Session 8: Design Patterns, Architectural Patterns

120

239

ReflectionProvides a mechanism for changingstructure and behavior of software dynamically.Support modification of fundamentalaspects: type structures and function call mechanismMeta-level makes the software self-awareBase-level includes application logic. Itsimplementation builds on the meta-level.

240

Reflection example

Page 121: Session 8: Design Patterns, Architectural Patterns

121

241

242

Reflection structure

Page 122: Session 8: Design Patterns, Architectural Patterns

122

243

Reflection example

Primitive

Type…

244

SuperType

Pointer? Or not

Field…

Page 123: Session 8: Design Patterns, Architectural Patterns

123

245

Reflection known UsesCLOS : generic function and generic functioninvocationMIP: run-time type information system for C++Pgen: persistence component for C++ basedon MIPOle2.0, CORBA (dynamic invocation)…

246

Reflection benefitsNo explicit modification of source codeChanging a software is easy: no need for visitors, factories and strategies patternsSupport for many kind of change

Page 124: Session 8: Design Patterns, Architectural Patterns

124

247

Reflection LiabilitiesModification at the meta-level can cause damage.Increased number of componentLower efficiencyNot all potential changes supported (onlythose supported by the MOP)Not all languages support reflection

248

Reflection example

Page 125: Session 8: Design Patterns, Architectural Patterns

125

249

Reflection example

public class Main {public static void main(String args[]) throws Exception {Point p = new Point();p.setX(3);p.setY(4);Cercle c = new Cercle();c.setPoint(p);c.setRadius(6);XMLEncoder e = new XMLEncoder(new BufferedOutputStream(newFileOutputStream(args[0])));e.writeObject(c);e.close();System.out.println(c);}}

250

Reflection example<?xml version="1.0" encoding="UTF-8"?><java version="1.4.2_03" class="java.beans.XMLDecoder"><object class="Cercle"><void property="point"><object class="Point"><void property="x"><int>3</int>

</void><void property="y"><int>4</int>

</void></object>

</void><void property="radius"><int>6</int>

</void></object>

</java>

Page 126: Session 8: Design Patterns, Architectural Patterns

126

251

Reflection examplepublic class Reread {public static void main(String args[])throws Exception {XMLDecoder d = new XMLDecoder(new

BufferedInputStream(newFileInputStream(args[0])));

Cercle c = (Cercle)d.readObject();d.close();

System.out.println(c);}}

252

Summary (C. Alexander)

It is possible to build an architecture by stringing together patterns, in a rather looseway. A building made like this, is an assemblyof patterns. It is not dense. It is not profound. But it is also possible to put patterns together in such way that many patterns overlap in thesame physical space: the building is verydense; it has many meanings captured in a small space; and through this density, itbecomes profound.

Page 127: Session 8: Design Patterns, Architectural Patterns

127

253

Drawbacks of Patterns

Patterns do not lead to direct code reuse. Individual Patterns are deceptively simple. Composition of different patterns can be verycomplex.Teams may suffer from pattern overload. Patterns are validated by experience anddiscussion rather than by automated testing. Integrating patterns into a software development process is a human-intensiveactivity.


Recommended