Software Engineering G22.2440-001...Software Architecture A software architecture is a description...

Preview:

Citation preview

1

1

Software EngineeringG22.2440-001

Session 7 – Sub-Topic 5Design/Architectural Patterns

Dr. Jean-Claude Franchitti

New York UniversityComputer Science Department

Courant Institute of Mathematical Sciences

2

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

2

3

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

4

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

3

5

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

6

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.

4

7

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.

8

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…

5

9

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.

10

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.

6

11

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.

12

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.

7

13

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.

14

menu

viewHighscore

Startturn=0

RollDice

turn++

Updatehighscore

Turn<10

[highscore] [start] [exit]

[true]

[false]

Activity Diagram

8

15

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

16

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

9

17

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

18

Layer: examples

10

19

Layer :Structure

20

Layer: Structure

11

21

Layer and components…

22

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…

12

23

Layers : Known Uses

• Virtual machines: JVM and binary code format• API : Layer that encapsulates lower layers• Information 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

24

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

Pattern– Dynamic exchange with Bridge Pattern

13

25

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…

26

Applying Layer Architecture

Play View High Score

Fichier ou BDD

UI

Core

Persistence

14

27

Package decomposition

UI<<layer>>

Core<<layer>>

Persist<<layer>>

Util<<subsystem>>

28

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

15

29

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

30

Singleton Structure

16

31

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

32

Package decomposition

UI<<layer>>

Core<<layer>>

Persist<<layer>>

Util<<subsystem>>

17

33

Observer

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

34

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

18

35

Observer: Structure

36

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

19

37

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)

38

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

20

39

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)

40

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)

21

41

Observer : Change Propagation: Die : Randomizer : DieView

1: getValue( )

2: setValue(int)

3: notifyObservers( )

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

3

: JLabel

6: setText(3)

42

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

22

43

Package decomposition

UI<<layer>>

Core<<layer>>

Persist<<layer>>

Util<<subsystem>>

44

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

23

45

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.

46

Structure

Produit

ProduitConcret

Facteur

Fabrication()UneOperation()

FacteurConcret

Fabrication()

produit=Fabrication()

return new ProduitConcret()

24

47

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

48

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

25

49

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

50

: 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

26

51

Summary

• 1 Architectural pattern : Layer• 2 Design Patterns : Observer, Factory• 1 Idiom : Singleton• Pb:

– Combining pattern to combine their forces…

52

27

53

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…

54

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

28

55

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 )

56

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

29

57

Command Example

58

Command Example

30

59

Command Structure

60

Command Structure

31

61

Command Consequencesn Command decouples the object that

invokes the operation from the one thatknows how to perform it.

n Commands are first-class objects. Theycan be manipulated and extended like anyother object.

n It's easy to add new Commands, because you don't have to change existing classes.

62

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)

32

63

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

64

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

33

65

Composite Example

66

Composite Example

34

67

Composite Structure

68

Applying Composite on Command

35

69

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

70

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

36

71

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

72

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

37

73

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

74

Proxy Example

38

75

Proxy Structure

76

Proxy benefitsn remote proxy can hide the fact that an

object resides in a different address space. n A virtual proxy can perform optimizations

such as creating an object on demand. n Both protection proxies and smart

references allow additional housekeepingtasks when an object is accessed.

39

77

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)

78

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

40

79

Adapter Example

80

Adapter Structure

41

81

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.

82

Visitor example

42

83

Visitor example

84

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

43

85

Visitor Structure

86

Visitor Structure

44

87

Visitor Consequencesn Visitor makes adding new operations easyn A visitor gathers related operations and

separates unrelated onesn Adding new Concrete Element classes is

hardn Visiting across class hierarchiesn Accumulating state.n Breaking encapsulation

88

Chain of responsibility

• Avoid 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.

45

89

90

Chain of Responsibility

46

91

Chain of Responsibility

92

Participants

• Handler (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 thechain.

47

93

Example…

• Awt 1.0

94

Strategy

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

48

95

Strategy…

96

Strategy

49

97

Participants

• Strategy (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.

98

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

50

99

State

• Allow an object to alter its behavior whenits internal state changes. The object willappear to change its class.

100

Example

51

101

Structure

102

Consequences

1. It localizes state-specific behavior andpartitions behavior for different states

2. It makes state transitions explicit3. State objects can be shared

52

103

Decorator

• Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.

104

Example

53

105

Example

106

Example

54

107

Structure

108

Applicability

• to add responsibilities to individual objectsdynamically and transparently, that is, without affecting other objects.

• for responsibilities that can be withdrawn• when extension by subclassing is

impractical

55

109

Consequences

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

110

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

56

111

Bridge

• Decouple an abstraction from itsimplementation so that the two can varyindependently.

112

Bridge

57

113

Bridge

114

Bridge Structure…

58

115

Bridge

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

116

ExampleUIManager

ListUI LabelUI

BasicLookAndFeel BasicLabelUI

JComponentComponentUI

createUI()installUI()paint()

#ui

MetalLookAndFeel

LAFState

LookAndFeel

getName()installColors()

lookAndFeel

MultiLookAndFeel MultiListUIMultiLabelUI

MetalLabelUI

BasicListUI

JList

#list

JLabel

59

117

118

Builder

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

60

119

Builder

120

Builder Structure…

61

121

Builder

122

Builder Consequences

1. It lets you vary a product's internalrepresentation

2. It isolates code for construction andrepresentation

3. It gives you finer control over theconstruction process

62

123

FlyWeight

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

124

FlyWeight

63

125

Flyweight: Structure

126

Flyweight example

64

127

Flyweight: Instances

128

Flyweight: Applicability

• Etat intrinsèque/extrinsèque…• Les états extrinsèques peuvent être

calculés…

65

129

Flyweight (il a rien compris… ☺)

130

Iterator

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

66

131

Iterator

132

Iterator example:

67

133

Example

134

Memento

• Without violating encapsulation, capture and externalize an object's internal state sothat the object can be restored to this state later.

68

135

Memento Structure…

136

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

69

137

Case Study

138

Design problems…

Document structure. The choice of internalrepresentation for the document affects nearly everyaspect of Lexi's design. All editing, formatting, displaying, and textual analysis will require traversingthe representation. The way 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 formattingpolicies? How do these policies interact with thedocument's internal representation?

70

139

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 andremove embellishments easily without affectingthe rest of the application. Supporting multiple look-and-feel standards.Lexi should adapt easily to different look-and-feel standards such as Motif and PresentationManager (PM) without major modification.

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 andremove embellishments easily without affectingthe rest of the application. Supporting multiple look-and-feel standards.Lexi should adapt easily to different look-and-feel standards such as Motif and PresentationManager (PM) without major modification.

71

141

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?

142

72

143

144

73

145

146

74

147

148

75

149

150

76

151

152

77

153

154

78

155

156

79

157

158

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.

80

159

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…

160

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

81

161

Layer: examples

162

Layer :Structure

82

163

Layer: Structure

164

Layer and components…

83

165

Layer and Facade DP…

166

Layer and Facade DP

84

167

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…

168

Layers : Known Uses

• Virtual machines: JVM and binary code format• API : Layer that encapsulates lower layers• Information 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

85

169

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

Pattern– Dynamic exchange with Bridge Pattern

170

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…

86

171

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.

172

Pipes and Filters: Example

87

173

Pipes and Filters: Structure

174

Pipes and Filters

88

175

Pipes and Filters: push pipeline

176

Pipes and Filters: pull pipeline

89

177

Pipes and Filters: push-pull pipeline

178

Pipes and Filters : ThreadedFilters

90

179

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 !!

180

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

91

181

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

182

[Sun Developpers]

92

183

184

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.

93

185

Blackboard Example

186

Blackboard Structure

94

187

Blackboard Structure

188

Blackboard Structure

95

189

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

190

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

96

191

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

192

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

97

193

194

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.

98

195

Broker example

196

Broker structure

99

197

Broker Structure

198

Broker Structure

100

199

Broker Structure

200

Broker Structure

101

201

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…

202

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

102

203

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

204

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

103

205

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.

206

MVC

104

207

MVC Structure

208

MVC Structure

105

209

MVC Structure

210

MVC Known UsesSmalltalkMFCET++: application FrameworkJava/Swing

106

211

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

212

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

107

213

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…

214

PAC Example

108

215

PAC Example

216

PAC Structure

109

217

Top Level PAC

• Abstraction : Global Data model • Presentation : Some Graphical elements• Control:

– Allow sub-agent to access abstraction– Manage hierarchy of PAC component – Manage info about interaction (log, check

applicability of triggered application…

218

110

219

PAC Structure

220

PAC Structure

111

221

PAC Structure

222

PAC Structure

112

223

PAC Known Uses

• Network 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

224

PAC Benefits

• Separation of concerns: Agent and inside an agent

• Support for change and extension• Support for multi-tasking: each PAC agent

can run its own thread on a differentcomputer…

113

225

PAC Liabilities

• Increased system complexity: Coordination of agents…

• Complex control component: coordonateaction inside agent and with other agents…

• Efficiency : data are propagated throughtthe tree…

• Applicability : Not a graphic editor whereeach object is a PAC agent…

226

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.

114

227

Microkernel

228

Microkernel Architecture

115

229

Microkernel Architecture

230

Microkernel Architecture

116

231

Microkernel Structure

232

Microkernel Structure

117

233

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

234

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

118

235

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

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

236

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…

119

237

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

knowledge of domain.

238

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.

120

239

Reflection example

240

121

241

Reflection structure

242

Reflection example

Primitive

Type…

122

243

SuperType

Pointer? Or not

Field…

244

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

123

245

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

246

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

124

247

Reflection example

248

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

125

249

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>

250

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

126

251

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.

252

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