g22_2440_001_c82

Upload: pierre-laporte

Post on 06-Jul-2018

214 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/17/2019 g22_2440_001_c82

    1/127

  • 8/17/2019 g22_2440_001_c82

    2/127

    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 collectiveexperience 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 orimplementation of a software system »« Patterns can be used to constructsoftware architectures with specificproperties… »

  • 8/17/2019 g22_2440_001_c82

    3/127

    5

    Becoming a Chess Master First 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 muststudy 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 DesignerMaster

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

    softwareThen learn the principles – e.g., structured programming, modular programming,

    object oriented programming, generic programming, etc.

    However, to truly master software design, onemust study the designs of other masters – These designs contain patterns must be understood,

    memorized, and applied repeatedlyThere are hundreds of these patterns

  • 8/17/2019 g22_2440_001_c82

    4/127

    7

    Software Architecture

    A software architecture is a description of thesubsystems and components of a softwaresystem 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

    Component

    A component is an encapsulated part of asoftware system. A component has aninterface.Components serve as the building blocks for

    the structure of a system. At a programming-language level,components may be represented asmodules, classes, objects or as a set of related functions.

  • 8/17/2019 g22_2440_001_c82

    5/127

    9

    Subsystems

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

    10

    Architectural Patterns

    An architectural Pattern expresses afundamental structural organization schemafor software systems. It provides a set ofpredefined subsystems, their responsibilities,and includes rules and guidelines fororganizing the relationships between them.

  • 8/17/2019 g22_2440_001_c82

    6/127

    11

    Design patterns

    A design pattern provides a scheme forrefining the subsystems or components of asoftware system, or the relation shipsbetween them. It describes a commonly-recurring structure of communicatingcomponents that solves a general designproblem within a particular context.

    12

    Idioms

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

  • 8/17/2019 g22_2440_001_c82

    7/127

    13

    Framework

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

    14

    First Example

    A Dice Game A Player rolls 10x 2 dicesIf result = 7, score=score + 10 points

    At the end, score of the player is registred inthe highscore table.

  • 8/17/2019 g22_2440_001_c82

    8/127

  • 8/17/2019 g22_2440_001_c82

    9/127

    17

    Design Stage

    Manage User InterfaceManage Persistence of highscore in a file orin relational databaseRealize a layered architecture : Apply theLayer Architectural Pattern

    18

    Layer

    Helps structure an application that can bedecomposed into groups of subtasks inwhich each group of subtasks is at aparticular level of abstraction.

  • 8/17/2019 g22_2440_001_c82

    10/127

    19

    Layer: examples

    20

    Layer :Structure

  • 8/17/2019 g22_2440_001_c82

    11/127

    21

    Layer: Structure

    22

    Layer and components…

  • 8/17/2019 g22_2440_001_c82

    12/127

    23

    Layers : Variants

    Relaxed 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 upper services…

    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 format

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

  • 8/17/2019 g22_2440_001_c82

    13/127

    25

    Layers: benefits

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

    Pattern – Dynamic exchange with Bridge Pattern

    26

    Layers: Liabilities

    Cascades of changing behavior Lower efficiencyUnnecessary work: functions of a layercalled many times for one service

    Difficulty of establishing correct granularity oflayers: Too few layers -> less benefits, toomany layers -> complexity and overhead…

  • 8/17/2019 g22_2440_001_c82

    14/127

    27

    Applying Layer Architecture

    Play View High Score

    Fichier ou BDD

    UI

    Core

    Persistence

    28

    Package decomposition

    UI

    Core

    Persist

    Util

  • 8/17/2019 g22_2440_001_c82

    15/127

    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.

  • 8/17/2019 g22_2440_001_c82

    16/127

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

    Player name : Stringscore : int = 0;

    Player()display()

    DiefaceValue : int = 1

    roll()Die()display()

    DiceGame$ dg = null

    DiceGame()getInstance()start()

    1

    -player

    1-dies

    22

    Singleton...

    Player name : Stringscore : int = 0;

    play()Player()

    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

  • 8/17/2019 g22_2440_001_c82

    17/127

    33

    Package decomposition

    UI

    Core

    Persist

    Util

    34

    Observer

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

  • 8/17/2019 g22_2440_001_c82

    18/127

    35

    Observer: Applicability

    A change to one object requires changing anunknown set of other objectsObject should be able to notify other objectsthat may not be known at the beginning

    36

    Observer: Structure

  • 8/17/2019 g22_2440_001_c82

    19/127

    37

    Observer: Consequences

    Abstract coupling between subject andobserver Support for broadcast communicationHard to maintain

    38

    Applying Observer PatternObservable

    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)

    0..*0..*

    Player

    name : Stringscore : int = 0;

    Player()display()

    (from Core)

    Die

    faceValue : int = 1

    roll()Die()display()

    (from Core)

  • 8/17/2019 g22_2440_001_c82

    20/127

    39

    Observer ViewObserver

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

    (from util)

    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)

    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)

  • 8/17/2019 g22_2440_001_c82

    21/127

    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)

  • 8/17/2019 g22_2440_001_c82

    22/127

    43

    Layered Architecture...

    DiefaceValue : int = 1

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

    Player name : Stringscore : int = 0;

    Player()display()

    Observer (from util)

    Observable(from util)

    0..*0..*

    Displayable

    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

    Core

    Persist

    Util

  • 8/17/2019 g22_2440_001_c82

    23/127

    45

    Pattern Factory Method

    Intent – 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 Method

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

  • 8/17/2019 g22_2440_001_c82

    24/127

    47

    Structure

    Produit

    ProduitConcret

    Facteur

    Fabrication()UneOperation()

    FacteurConcret

    Fabrication()

    produit=Fabrication()

    return new ProduitConcret()

    48

    Factory method

    Consequences – Provide hooks for subclasses – connects parallel class hierarchies

    Known uses

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

    creation) – Orbix ORB for generating PROXY object

  • 8/17/2019 g22_2440_001_c82

    25/127

    49

    « Persist » Layer

    Persistence 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

  • 8/17/2019 g22_2440_001_c82

    26/127

    51

    : RealPlayer : S rKit : HighScoreSr : DiceGame

    2: getInstance( )

    3: DiceGame( )

    1: SrKit( )

    4: makeKit( ) 5: HighScoreSr( )

    Attention!DiceGame voit SrKit commeun PersistKit et HighScoreSrcomme un HighScore

    6: load( )

    7: quit( ) 8: getInstance( )

    9: save( )

    Seul le Realplayer sait qu'ilutilise un SrKit ! DiceGamenon !

    Applying Factory

    52

    Summary

    1 Architectural pattern : Layer 2 Design Patterns : Observer, Factory1 Idiom : SingletonPb: – Combining pattern to combine their forces…

  • 8/17/2019 g22_2440_001_c82

    27/127

    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…

  • 8/17/2019 g22_2440_001_c82

    28/127

    55

    Naive solutionBank

    add Account(S tring name, int amo unt) : Accountwithdrawal(int ida, int amount) : voiddep osit(int ida, int amout) : voidtransfer(int ida1, int id a2, int amount) : voidgetAccount(int ida) : A ccount

    Accountint amountint ida

    withdraw(int a )

    deposit(int a) Account(int ida )

    Customer String 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

    t ra n s f e 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 t A c c o u n t( 1 )

    g e t A c c o u n t( 2 )

  • 8/17/2019 g22_2440_001_c82

    29/127

    57

    Applying Command Pattern…

    Encapsulate a request as an object, therebyletting you parameterize clients with differentrequests, queue or log requests, and supportundoable operations.

    58

    Command Example

  • 8/17/2019 g22_2440_001_c82

    30/127

  • 8/17/2019 g22_2440_001_c82

    31/127

    61

    Command Structure

    62

    Command Consequences

    Command decouples the object thatinvokes the operation from the one thatknows how to perform it.Commands are first-class objects. They

    can be manipulated and extended like anyother object.It's easy to add new Commands, becauseyou don't have to change existing classes.

  • 8/17/2019 g22_2440_001_c82

    32/127

    63

    Applying Command Pattern

    Ac countint amountint ida

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

    Customer String name;int idc

    Client(String name, int idc)

    ida : int11..n 1

    ida : int1..n

    Withdrawalida : intamount : int

    do() : voidundo:void()

    Command b : 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()

    Transfer ida1 : 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( )

  • 8/17/2019 g22_2440_001_c82

    33/127

    65

    Composite Pattern

    Compose objects into tree structures torepresent part-whole hierarchies. Compositelets clients treat individual objects andcompositions of objects uniformly.

    66

    Composite Example

  • 8/17/2019 g22_2440_001_c82

    34/127

    67

    Composite Example

    68

    Composite Structure

  • 8/17/2019 g22_2440_001_c82

    35/127

    69

    Applying Composite on Command

    70

    Applying Composite

    Accountint amountint ida

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

    Customer String 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 : i nt, amount : int)

    Macrocom

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

    Command b : banque

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

    +receiver

    0..n0..n

  • 8/17/2019 g22_2440_001_c82

    36/127

    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)

    Customer String name;int idc

    Client(String name, int i dc)

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

  • 8/17/2019 g22_2440_001_c82

    37/127

    73

    And So on…

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

    74

    Proxy Pattern

    Provide a surrogate or placeholder foranother object to control access to it.

  • 8/17/2019 g22_2440_001_c82

    38/127

    75

    Proxy Example

    76

    Proxy Structure

  • 8/17/2019 g22_2440_001_c82

    39/127

    77

    Proxy benefits

    remote proxy can hide the fact that anobject resides in a different address space.

    A virtual proxy can perform optimizationssuch as creating an object on demand.Both protection proxies and smartreferences 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

    (fromremotecommand)

    RemoteObservable

    changed: boolean

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

    (fromremotecommand)

    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

    (fromremotecommand)

    BankServerI

    execute(arg0: Command) : void

    (from remotecommand)

    RemoteObserver

    update(arg0: Object) : void

    (from remotecommand)

    RegisterObserver

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

    (fromremotecommand)

    ro

    Command

    execute() : voidunexecute() : voidCommand()

    (from remotecommand)

    MacroCommand

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

    (fromremotecommand)

  • 8/17/2019 g22_2440_001_c82

    40/127

    79

    Adapter Pattern

    Convert the interface of a class into another interface clients expect. Adapter lets classeswork together that couldn't otherwisebecause of incompatible interfaces.

    80

    Adapter Example

  • 8/17/2019 g22_2440_001_c82

    41/127

    81

    Adapter Structure

    82

    Visitor Pattern

    Represent an operation to be performed onthe elements of an object structure. Visitor lets you define a new operation withoutchanging the classes of the elements onwhich it operates.

  • 8/17/2019 g22_2440_001_c82

    42/127

    83

    Visitor example

    84

    Visitor example

  • 8/17/2019 g22_2440_001_c82

    43/127

    85

    Visitor applicability

    many 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

  • 8/17/2019 g22_2440_001_c82

    44/127

    87

    Visitor Structure

    88

    Visitor Consequences

    Visitor makes adding new operations easy A visitor gathers related operations and

    separates unrelated ones Adding new Concrete Element classes is

    hard Visiting across class hierarchies Accumulating state. Breaking encapsulation

  • 8/17/2019 g22_2440_001_c82

    45/127

    89

    Chain of responsibility

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

    90

  • 8/17/2019 g22_2440_001_c82

    46/127

    91

    Chain of Responsibility

    92

    Chain of Responsibility

  • 8/17/2019 g22_2440_001_c82

    47/127

    93

    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.

    94

    Example…

    Awt 1.0

  • 8/17/2019 g22_2440_001_c82

    48/127

    95

    Strategy

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

    96

    Strategy…

  • 8/17/2019 g22_2440_001_c82

    49/127

    97

    Strategy

    98

    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.

  • 8/17/2019 g22_2440_001_c82

    50/127

    99

    Strategy…

    B u t to n( fr o m a w t )

    B o r d e r L a y o u t( fr o m a w t )

    C o m p o n e nt( fr o m a w t )

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

    L a y o ut M a n a g e r 2( fr o m a w t )

    < < I n t e r f a c e > >

    C o n ta i ne r ( fr o m a w t )

    c o m p o n e n t []

    L a y o u t M a n a g e r ( fr o m a w t )

    < < I n t e r f a c e > >la y o u t M g r

    100

    State

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

  • 8/17/2019 g22_2440_001_c82

    51/127

    101

    Example

    102

    Structure

  • 8/17/2019 g22_2440_001_c82

    52/127

    103

    Consequences

    1. It localizes state-specific behavior and partitions behavior for different states

    2. It makes state transitions explicit 3. State objects can be shared

    104

    Decorator

    Attach additional responsibilities to an objectdynamically. Decorators provide a flexiblealternative to subclassing for extendingfunctionality.

  • 8/17/2019 g22_2440_001_c82

    53/127

    105

    Example

    106

    Example

  • 8/17/2019 g22_2440_001_c82

    54/127

    107

    Example

    108

    Structure

  • 8/17/2019 g22_2440_001_c82

    55/127

    109

    Applicability

    to 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

    Consequences

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

    hierarchy 3. A decorator and its component aren't

    identical 4. Lots of little objects

  • 8/17/2019 g22_2440_001_c82

    56/127

    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() : FileDescriptor initIDs() : 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

    Bridge

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

  • 8/17/2019 g22_2440_001_c82

    57/127

    113

    Bridge

    114

    Bridge

  • 8/17/2019 g22_2440_001_c82

    58/127

    115

    Bridge Structure…

    116

    Bridge

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

  • 8/17/2019 g22_2440_001_c82

    59/127

    117

    ExampleUIManager

    ListUI LabelUI

    BasicLookAndFeel BasicLabelUI

    JComponent ComponentUI

    createUI()installUI()paint()

    #ui

    MetalLookAndFeel

    LAFState

    LookAndFeel

    getName()installColors()

    lookAndFeel

    MultiLookAndFeelMultiListUI

    MultiLabelUI

    MetalLabelUI

    BasicListUI

    JList

    #list

    JLabel

    118

  • 8/17/2019 g22_2440_001_c82

    60/127

    119

    Builder

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

    120

    Builder

  • 8/17/2019 g22_2440_001_c82

    61/127

    121

    Builder Structure…

    122

    Builder

  • 8/17/2019 g22_2440_001_c82

    62/127

    123

    Builder Consequences

    1. It lets you vary a product's internal representation

    2. It isolates code for construction and representation

    3. It gives you finer control over theconstruction process

    124

    FlyWeight

    Use sharing to support large numbers offine-grained objects efficiently.

  • 8/17/2019 g22_2440_001_c82

    63/127

    125

    FlyWeight

    126

    Flyweight: Structure

  • 8/17/2019 g22_2440_001_c82

    64/127

    127

    Flyweight example

    128

    Flyweight: Instances

  • 8/17/2019 g22_2440_001_c82

    65/127

    129

    Flyweight: Applicability

    Etat intrinsèque/extrinsèque…Les états extrinsèques peuvent êtrecalculés…

    130

    Flyweight (il a rien compris… ☺)

  • 8/17/2019 g22_2440_001_c82

    66/127

    131

    Iterator

    Provide a way to access the elements of anaggregate object sequentially withoutexposing its underlying representation

    132

    Iterator

  • 8/17/2019 g22_2440_001_c82

    67/127

    133

    Iterator example:

    134

    Example

  • 8/17/2019 g22_2440_001_c82

    68/127

    135

    Memento

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

    136

    Memento Structure…

  • 8/17/2019 g22_2440_001_c82

    69/127

    137

    Memento…

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

    138

    Case Study

  • 8/17/2019 g22_2440_001_c82

    70/127

    139

    Design problems… Document structure. The choice of internal representation

    for the document affects nearly every aspect of Lexi'sdesign. All editing, formatting, displaying, and textualanalysis will require traversing the representation. Theway we organize this information will impact the design ofthe rest of the application.

    Formatting. How does Lexi actually arrange text andgraphics into lines and columns? What objects areresponsible 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 dropshadows that embellish the WYSIWYG documentinterface. Such embellishments are likely tochange as Lexi's user interface evolves. Henceit's important to be able to add and removeembellishments easily without affecting the rest ofthe application.

    Supporting multiple look-and-feel standards. Lexishould adapt easily to different look-and-feelstandards such as Motif and PresentationManager (PM) without major modification.

  • 8/17/2019 g22_2440_001_c82

    71/127

    141

    Design problems… Embellishing the user interface. Lexi's user

    interface includes scroll bars, borders, and dropshadows that embellish the WYSIWYG documentinterface. Such embellishments are likely tochange as Lexi's user interface evolves. Henceit's important to be able to add and removeembellishments easily without affecting the rest ofthe 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. Howdoes 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?

  • 8/17/2019 g22_2440_001_c82

    72/127

    143

    144

  • 8/17/2019 g22_2440_001_c82

    73/127

    145

    146

  • 8/17/2019 g22_2440_001_c82

    74/127

    147

    148

  • 8/17/2019 g22_2440_001_c82

    75/127

    149

    150

  • 8/17/2019 g22_2440_001_c82

    76/127

    151

    152

  • 8/17/2019 g22_2440_001_c82

    77/127

    153

    154

  • 8/17/2019 g22_2440_001_c82

    78/127

    155

    156

  • 8/17/2019 g22_2440_001_c82

    79/127

    157

    158

  • 8/17/2019 g22_2440_001_c82

    80/127

    159

    Summary (C. Alexander)

    It is possible to create building architectures bystringing 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 insuch way that many patterns overlap in thesame physical space: the building is verydense; it has many meanings captured in asmall 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…

  • 8/17/2019 g22_2440_001_c82

    81/127

    161

    Layer

    helps structure application that can bedecomposed into groups of subtasks inwhich each group of subtasks is at aparticular level of abstraction.

    162

    Layer: examples

  • 8/17/2019 g22_2440_001_c82

    82/127

    163

    Layer :Structure

    164

    Layer: Structure

  • 8/17/2019 g22_2440_001_c82

    83/127

    165

    Layer and components…

    166

    Layer and Facade DP…

  • 8/17/2019 g22_2440_001_c82

    84/127

    167

    Layer and Facade DP

    168

    Layers : Variants

    Relaxed 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 upper services…

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

  • 8/17/2019 g22_2440_001_c82

    85/127

    169

    Layers : Known UsesVirtual machines: JVM and binary code format

    API : 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: benefits

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

    Pattern – Dynamic exchange with Bridge Pattern

  • 8/17/2019 g22_2440_001_c82

    86/127

    171

    Layers: Liabilities

    Cascades of changing behavior Lower efficiencyUnnecessary work: functions of a layercalled many times for one serviceDifficulty of establishing correct granularity oflayers: Too few layers -> less benefits, toomany layers -> complexity and overhead…

    172

    Pipes and Filters

    Provides 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 of families of related systems.

  • 8/17/2019 g22_2440_001_c82

    87/127

    173

    Pipes and Filters: Example

    174

    Pipes and Filters: Structure

  • 8/17/2019 g22_2440_001_c82

    88/127

    175

    Pipes and Filters

    176

    Pipes and Filters: push pipeline

  • 8/17/2019 g22_2440_001_c82

    89/127

    177

    Pipes and Filters: pull pipeline

    178

    Pipes and Filters: push-pull pipeline

  • 8/17/2019 g22_2440_001_c82

    90/127

    179

    Pipes and Filters : Threaded Filters

    180

    Pipes and Filters: Known Uses

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

  • 8/17/2019 g22_2440_001_c82

    91/127

    181

    Pipes and Filters Benefits

    No intermediate file necessary (but possible)Flexibility by filter exchangeFlexibility by recombinationReuse of filter componentsRapid prototyping of pipelineEfficiency by parallel processing

    182

    Pipes and Filters Liabilities

    Sharing state information is expensive orinflexibleEfficiency gain by parallel processing is oftenan illusion

    – Cost of data transfer, filters that consume alldata before one output, context switch on onecomputer, synchronization of filters via pipes

    Data transformation overheadError Handling

  • 8/17/2019 g22_2440_001_c82

    92/127

    183

    [Sun Developpers]

    184

  • 8/17/2019 g22_2440_001_c82

    93/127

  • 8/17/2019 g22_2440_001_c82

    94/127

    187

    Blackboard Structure

    188

    Blackboard Structure

  • 8/17/2019 g22_2440_001_c82

    95/127

  • 8/17/2019 g22_2440_001_c82

    96/127

    191

    Blackboard known uses

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

    192

    Blackboard benefits

    Experimentation: different algo, differentcontrol heuristicsChangeability and maintainability: separationdata/control.

    Reusable knowledge sourceSupport for Fault tolerance and robustness:Tolerance of noisy data…

  • 8/17/2019 g22_2440_001_c82

    97/127

    193

    Blackboard Liabilities

    Difficulty of testing: no deterministic algoNo good solution is guaranteed.Difficulty of establishing a good controlstrategyLow efficiency: (rejecting wrong hypothesis)High development effort : trial-and-error programmingNo support for parallelism

    194

  • 8/17/2019 g22_2440_001_c82

    98/127

    195

    Broker

    Used to structure distributed softwaresystems with decoupled components thatinteract by remote service invocation.

    A broker component is responsible forcoordinating communication, such asforwarding request, as well as fortransmitting result and exception.

    196

    Broker example

  • 8/17/2019 g22_2440_001_c82

    99/127

    197

    Broker structure

    198

    Broker Structure

  • 8/17/2019 g22_2440_001_c82

    100/127

    199

    Broker Structure

    200

    Broker Structure

  • 8/17/2019 g22_2440_001_c82

    101/127

    201

    Broker Structure

    202

    Broker Variants

    Direct 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 morethan one server…

    Callback broker system: event driven…

  • 8/17/2019 g22_2440_001_c82

    102/127

    203

    Known Uses

    CORBAIBM SOM/DSOMMicrosoft Ole 2.xWWW

    ATM-P: Message passing broker.Telecommunication switching system basedon ATM.

    204

    Broker benefits

    Location transparencyChangeability and extensibility ofcomponentsPortability of a broker system (Layered)

    Interoperability between brokers (bridge)Reusability (of services)

  • 8/17/2019 g22_2440_001_c82

    103/127

    205

    Broker Liabilities

    Restricted efficiency (indirection layer)Lower Fault tolerance: fault a broker or aserver… 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.

  • 8/17/2019 g22_2440_001_c82

    104/127

    207

    MVC

    208

    MVC Structure

  • 8/17/2019 g22_2440_001_c82

    105/127

    209

    MVC Structure

    210

    MVC Structure

  • 8/17/2019 g22_2440_001_c82

    106/127

    211

    MVC Known Uses

    SmalltalkMFCET++: application FrameworkJava/Swing

    212

    MVC benefits

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

  • 8/17/2019 g22_2440_001_c82

    107/127

    213

    MVC LiabilitiesIncreased complexityPotential for excessive number of updatesIntimate connection between view andcontroller Close coupling of views and controllers to amodelInefficiency of data access in viewInevitability of change to view and controller when portingDifficulty of using MVC with modern user-interface tools

    214

    Presentation-Abstraction-Control

    PAC define a hierarchy of cooperatingagents.Each agent consists of three components:presentation, abstraction, control.

    Separates human computer interaction fromits functional core and its communicationwith other agents…

  • 8/17/2019 g22_2440_001_c82

    108/127

    215

    PAC Example

    216

    PAC Example

  • 8/17/2019 g22_2440_001_c82

    109/127

  • 8/17/2019 g22_2440_001_c82

    110/127

    219

    220

    PAC Structure

  • 8/17/2019 g22_2440_001_c82

    111/127

    221

    PAC Structure

    222

    PAC Structure

  • 8/17/2019 g22_2440_001_c82

    112/127

    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 wholenetwork

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

  • 8/17/2019 g22_2440_001_c82

    113/127

    225

    PAC Benefits

    Separation of concerns: Agent and inside anagentSupport for change and extensionSupport for multi-tasking: each PAC agentcan run its own thread on a differentcomputer…

    226

    PAC Liabilities

    Increased system complexity: Coordinationof 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…

  • 8/17/2019 g22_2440_001_c82

    114/127

  • 8/17/2019 g22_2440_001_c82

    115/127

    229

    Microkernel Architecture

    230

    Microkernel Architecture

  • 8/17/2019 g22_2440_001_c82

    116/127

    231

    Microkernel Architecture

    232

    Microkernel Structure

  • 8/17/2019 g22_2440_001_c82

    117/127

    233

    Microkernel Structure

    234

    Microkernel variants

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

  • 8/17/2019 g22_2440_001_c82

    118/127

    235

    Microkernel known Uses

    Mach (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 uses

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

    win32 server

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

  • 8/17/2019 g22_2440_001_c82

    119/127

    237

    Microkernel Benefits

    Portability : 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 Liabilities

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

    knowledge of domain.

  • 8/17/2019 g22_2440_001_c82

    120/127

    239

    Reflection

    Provides a mechanism for changingstructure and behavior of softwaredynamically.Support modification of fundamentalaspects: type structures and function callmechanismMeta-level makes the software self-aware

    Base-level includes application logic. Itsimplementation builds on the meta-level.

    240

    Reflection example

  • 8/17/2019 g22_2440_001_c82

    121/127

    241

    242

    Reflection structure

  • 8/17/2019 g22_2440_001_c82

    122/127

    243

    Reflection example

    Primitive

    Type…

    244

    SuperType

    Pointer? Or not

    Field…

  • 8/17/2019 g22_2440_001_c82

    123/127

    245

    Reflection known Uses

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

    246

    Reflection benefits

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

  • 8/17/2019 g22_2440_001_c82

    124/127

    247

    Reflection Liabilities

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

    248

    Reflection example

  • 8/17/2019 g22_2440_001_c82

    125/127

    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

    3

    4

    6

  • 8/17/2019 g22_2440_001_c82

    126/127

    251

    Reflection example public 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 bystringing 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 insuch way that many patterns overlap in thesame physical space: the building is verydense; it has many meanings captured in asmall space; and through this density, itbecomes profound.

  • 8/17/2019 g22_2440_001_c82

    127/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 softwaredevelopment process is a human-intensiveactivity.