5DesignPatterns2 ppt

download 5DesignPatterns2 ppt

of 33

Transcript of 5DesignPatterns2 ppt

  • 8/7/2019 5DesignPatterns2 ppt

    1/33

    2

    Lecture Notes onDesign Pat terns II

    Bernd Bruegge

    Technische Universitt Mnchen

    Lehrstuh l fr Angewand te Softwaretechnik

    June 10, 1998

  • 8/7/2019 5DesignPatterns2 ppt

    2/33

    Odds and Ends

    v February 2, lecture on Security

  • 8/7/2019 5DesignPatterns2 ppt

    3/33

    Outline

    v Review of design p attern concepts

    w What is a design p attern?

    w Mod ifiable designs

    v Review of design patternsw Adapter: converting interfaces

    w Bridge: decoup ling in terface and imp lemen tation

    w Facade: simp lifying interfaces

    v New p atterns:

    w Proxy

    w Command

    w Observer

  • 8/7/2019 5DesignPatterns2 ppt

    4/33

    W hat is a design pat tern? (Take 2)

    A design p attern is

    a template solution to a recurring d esign problem

    w Look before re-inventing the wh eel just one more time

    reusable design knowledge

    w High er level than link lists or bin ary trees

    w Lower level than app lication framework s

    an example of modifiable and reusable design

    w Learnin g to design starts by stud ying other d esigns

  • 8/7/2019 5DesignPatterns2 ppt

    5/33

    W hy are modifiable designs important?

    A modifiable design enables

    an iterative and incremental development cycle

    w concurrent development

    w risk management

    w flexib ility to change

    to minimize the introd uction of new problems whenfixing old ones

    to d eliver more functionality after initial delivery

  • 8/7/2019 5DesignPatterns2 ppt

    6/33

    W hat makes a design modifiable?

    v Low coup ling and high coherence

    v Clear depend encies

    v Explicit assumptions

    How d o design patterns help?

    v They are generalized from existing systems

    v They provide a shared vocabulary to designers

    v They provide examples of modifiable designs

    w Abstract classes

    w Delegation

  • 8/7/2019 5DesignPatterns2 ppt

    7/33

    Inheritance: class v s. inheritance

    v Interface inheritance(i.e., subtyp ing):

    w describes when differenttypes of ob jects can b e used inp lace of each other

    v Class inheritance:

    w

    an ob jects implemen tation isdefined in terms of theimp lementation of another. PutAt()

    RemoveAt()

    HashTable

    Add()Remove()

    Set

    PutAt()RemoveAt()

    HashTable

    PutAt()RemoveAt()

    Table

    PutAt()RemoveAt()

    BTree

  • 8/7/2019 5DesignPatterns2 ppt

    8/33

    Interface inheritance vs. class inheritance

    v Interface inheritance

    w separates interface and implemen tation

    w imp lementations m ay be transparently sub stituted

    w decreases coup ling

    v Class inheritance

    w introdu ces depen den ces among an ancestor and its descend ents(inh erited state)

    w mixes interface specification an d imp lemen tation

    w can be achieved with delegation in stead

    v Design p atterns show how to avoid class inheritance withexamples of interface inheritance and delegation

  • 8/7/2019 5DesignPatterns2 ppt

    9/33

    Interface and class inheritance in Java

    v An interface defines constants and abstract methods.

    w An in terface can extend(i.e., inherit from ) zero, one, or m anyinterfaces.

    w An interface does not define any b ehavior or attribu tes

    v A class defines attributes and methods.

    w A class can extend(i.e., inh erit beh avior and attribu tes from)zero or on e class.

    w A class can implement(i.e., comply w ith) zero, one, or man yinterfaces in add ition to extend ing a super class.

    v Abstract classes shou ld be realized by interfaces in Java.

    v Concrete classes should be realized by classes in Java.

  • 8/7/2019 5DesignPatterns2 ppt

    10/33

    Rev iew of last years pat terns

    v Bridge

    w Decouple an abstraction form its imp lemen tation so that thetwo can vary ind epend ently.

    v

    Adapterw Convert th e in terface of a class into an other in terface clients

    expect. Adapter lets classes work together that couldntotherwise because of incomp atible in terfaces.

    v Facade

    w Provide a unified interface to a set of interfaces in asub system. Facade d efines a h igher-level interface that m akesthe su bsystem easier to use.

  • 8/7/2019 5DesignPatterns2 ppt

    11/33

    Rev iew : Bridge pat tern

    v Delegation is used to bind an Abstraction andConcreteImplementor.

    v Interface inheritance is used to refine Abstraction andImplementor.

    v Implementor can be implemented as a Java interfaceinstead of a class.

    Client

    RefinedAbstractionConcrete

    ImplementorB

    Concrete

    ImplementorA

    ImplementorAbstraction

    imp

  • 8/7/2019 5DesignPatterns2 ppt

    12/33

    Bridge pat tern example

    v Window hierarchy implements h igh level behavior

    v WindowImp hierarchy imp lements device level behavior

    v Bridge patterns can be used for implementing a layereddesign.

    Client

    IconWindow PMWindowXWindow

    WindowImpWindow

    imp

    TransientWindow

  • 8/7/2019 5DesignPatterns2 ppt

    13/33

    JAMES Bridge Exam ple

    public interface SeatImplementation {

    public int GetPosition();

    public void SetPosition(int newPosition);

    }

    public class AimSeat implements SeatImplementation {

    public int GetPosition() {

    // actual call to the simulator

    }

    }

    Client

    SARTSeatAIMSeat

    SeatImplementationSeat

    imp

  • 8/7/2019 5DesignPatterns2 ppt

    14/33

    v Delegation is used tobind an Adapter and an Adaptee

    v Interface inheritance is specify the interface of the

    Adapter class.v Targetand Adaptee (usually) pre-exist the Adapter.

    v Target may be realized as an interface in Java.

    Rev iew : Adapter pat tern

    Client

    Target

    Request()

    Adaptee

    ExistingRequest()

    Adapter

    Request()

    adaptee

  • 8/7/2019 5DesignPatterns2 ppt

    15/33

    Adapter pat tern example

    public class ServicesEnumeration

    implements Enumeration {

    public boolean hasMoreElements() {

    return this.currentServiceIdx

  • 8/7/2019 5DesignPatterns2 ppt

    16/33

    Rev iew : facade pat tern

    Compiler

    compile(s)

    ParseNode

    create()

    Lexer

    getToken()

    CodeGenerator

    create()

    Parser

    generateParseTree()

    Optimizer

    create()

    Compiler

  • 8/7/2019 5DesignPatterns2 ppt

    17/33

    New pat terns

    v Structural pattern

    w Proxy

    v Behavioral pattern

    w Command

    w Observer

  • 8/7/2019 5DesignPatterns2 ppt

    18/33

    Proxy pat tern

    v Interface inheritance is used to sp ecify the interfaceshared by Proxy and RealSubject.

    v Delegation is used to catch and forward accesses to theRealSubject .

    v Proxy patterns can be u sed for lazy evaluation and forremote invocation.

    v Proxy patterns can be imp lemented with a Java interface.

    Subject

    Request()

    RealSubject

    Request()

    Proxy

    Request()

    realSubject

  • 8/7/2019 5DesignPatterns2 ppt

    19/33

    Proxy pat tern example

    v Images are stored and loaded separately from text

    v If a RealImage is not loaded a ProxyImage displays agrey rectangle in place of the image

    v The client cannot tell that it is dealing with a ProxyImageinstead of a RealImage

    v A proxy pattern can be easily overlayed with a Bridge

    ImageboundingBox()

    draw()

    realSubject RealImageboundingBox()

    draw()

    ProxyImageboundingBox()

    draw()

  • 8/7/2019 5DesignPatterns2 ppt

    20/33

    Structural pat tern: summary

    v Adapters, Bridges, Facades, and Proxies are variationson a single theme:

    w examp les of delegation an d in terface inh eritance

    w decoup le two or more classes to reduce coup ling

    w introd uce an abstract class enab ling fu ture extensions

    v Behavioral patterns p rovide similar benefits for controlflow.

  • 8/7/2019 5DesignPatterns2 ppt

    21/33

    Command pat tern

    v Encapsulate a request as an object, thereby letting you

    w parameterize clients with d ifferent requests,

    w qu eue or log requests, and

    w sup port un doable op erations. (p . 233)

    v Uses:

    w Undo queues

    w Datab ase transaction bu ffering

  • 8/7/2019 5DesignPatterns2 ppt

    22/33

    Comm and pat tern: undo queue

  • 8/7/2019 5DesignPatterns2 ppt

    23/33

    Command pat tern: classes

    v Client creates a ConcreteCommand and bind s it with aReceiver.

    v Client hands the ConcreteCommand over to the Invokerwhich stores it.

    v The Invoker has the responsibility to execute orundo Commands.

    Commandexecute()

    undo()

    Receiver

    action()

    Client

    Invoker

    ConcreteCommand

    execute()undo()

  • 8/7/2019 5DesignPatterns2 ppt

    24/33

    Command pat tern: typical sequence

    rectangle anEditor moveCommand undoQueue

    newCommand(info)

    store(aCommand)

    execute(info)move(x, y)

  • 8/7/2019 5DesignPatterns2 ppt

    25/33

    Command pat tern: inst ance diagram

    aRectangle

    moveCommand1

    status = #d one

    coordObject1

    x=10, y=20

    undoQueue

    moveCommand2

    status = #d one

    coordObject2

    x=20, y=30

    moveCommand3status = #u nd one

    coordObject3x=30, y=50

  • 8/7/2019 5DesignPatterns2 ppt

    26/33

    Observer pat tern

    v Define a one-to-many dependency between objects sothat when one object changes state, all its dependents arenotified and updated automatically. (p. 293)

    v Uses:

    w Main taining consistency across redu ndan t state

    w Op tmizing batch chan ges when maintaining consistency

  • 8/7/2019 5DesignPatterns2 ppt

    27/33

    Observer pat tern (cont inued)

    9DesignPatterns2.ppt

    Observers Subject

  • 8/7/2019 5DesignPatterns2 ppt

    28/33

    Observer pat tern (cont d)

    Observerupdate()

    Subject

    attach(observer)detach(observer)

    notify()

    ConcreteSubjectgetState()

    setState(newState)

    subjectState

    ConcreteObserver

    update()

    observerState

    observers

    subject

    *

    v The Subject represents the actual state, the Observersrepresent d ifferent views of the state.

    v Observer can be imp lemented as a Java interface.

    v Subject is a super class (needs to store the observersvector) notan interface.

  • 8/7/2019 5DesignPatterns2 ppt

    29/33

    Observer pat tern sequence

    aFile anInfoWindow aDirectoryWindow

    setName(foo)

    update()

    getName()

    update()

    getName()

    notify()

  • 8/7/2019 5DesignPatterns2 ppt

    30/33

    Observer pat tern exam ple: Java implementat ion

    // import java.util;

    public class Observable extends Object {

    public void addObserver(Observer o);

    public void deleteObserver(Observer o);

    public boolean hasChanged();

    public void notifyObservers();

    public void notifyObservers(Object arg);

    }

    public abstract interface Observer {

    public abstract void update(Observable o, Object arg);

    }

  • 8/7/2019 5DesignPatterns2 ppt

    31/33

    Three object type archit ecture

    v Interface objects

    w imp lement the interaction with th e user

    w constructed from UI comp onen ts

    w sub ject to most m odification

    v

    Control objectsw imp lement the transactions w ith the u ser

    w constructed w ith Comm and objects

    w modified frequen tly bu t less often than in terface objects

    v Entity objects

    w represent the domain m odel

    w often represent persistent data

    w least often modified

  • 8/7/2019 5DesignPatterns2 ppt

    32/33

    Three object type archit ecture (cont inued)

    Menu

    MoveCommand

    Rectangle

    DrawingView

    RectangleInfo

    UndoQueue

    Interface objects Control objects

    Ent ity objects

  • 8/7/2019 5DesignPatterns2 ppt

    33/33

    Summary

    v Design patterns provide solutions to comm on decoup lingproblems.

    v Design patterns result into extensible models and code.

    v Design patterns can be used as is or as examples ofinterface inheritance and delegation.

    v

    Design p atterns apply the same principles to structureand to behavior.