dpatterns overview examples

Upload: shoaib501

Post on 05-Apr-2018

226 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/2/2019 Dpatterns Overview Examples

    1/81

    DESIGN PATTERN OVERVIEW

    AND EXAMPLE CODE

  • 8/2/2019 Dpatterns Overview Examples

    2/81

    Motivation and Concept

    OO systems exploit recurring design structuresthat promoteAbstraction

    Flexibility Modularity

    Elegance

    Therein lies valuable design knowledge

    Problem: capturing, communicating, andapplying this knowledge

    E.

    Gamma,R.Helm,R.Johnson,J

    .VlissidesandAddison-Wesley

  • 8/2/2019 Dpatterns Overview Examples

    3/81

    What Is a Design Pattern?

    A design pattern Is a common solution to a recurring problem in

    design

    Abstracts a recurring design structure

    Comprises class and/or object Dependencies

    Structures

    Interactions

    Conventions Names & specifies the design structure explicitly

    Distils design experience

    E.

    Gamma,R.Helm,R.Johnson,J

    .VlissidesandAddison-Wesley

  • 8/2/2019 Dpatterns Overview Examples

    4/81

    What Is a Design Pattern?

    A design pattern has 4 basic parts: 1. Name

    2. Problem

    3. Solution

    4. Consequences and trade-offs of application Language- and implementation-independent

    A micro-architecture

    Adjunct to existing methodologies (Unified, OMT, etc.)

    No mechanical application The solution needs to be translated into concrete terms in the

    application context by the developer

    E.

    Gamma,R.Helm,R.Johnson,J

    .VlissidesandAddison-Wesley

  • 8/2/2019 Dpatterns Overview Examples

    5/81

    Goals

    Codify good design Distil and disseminate experience Aid to novices and experts alike Abstract how to think about design

    Give design structures explicit names Common vocabulary Reduced complexity Greater expressiveness

    Capture and preserve design information

    Articulate design decisions succinctly Improve documentation

    Facilitate restructuring/refactoring Patterns are interrelated Additional flexibility

    E.

    Gamma,R.Helm,R.Johnson,J

    .VlissidesandAddison-Wesley

  • 8/2/2019 Dpatterns Overview Examples

    6/81

    Design Pattern Catalogues

    GoF (the gang of four) catalogue

    Design Patterns: Elements of Reusable

    Object-Oriented Software, Gamma, Helm,

    Johnson, Vlissides, Addison-Wesley, 1995

    POSA catalogue

    Pattern-Oriented Software Architecture,

    Buschmann, et al.; Wiley, 1996

  • 8/2/2019 Dpatterns Overview Examples

    7/81

    Classification of GoF Design

    Pattern

    Creational Structural Behavioral

    Factory Method

    Abstract Factory

    Builder

    Prototype

    Singleton

    Adapter

    Bridge

    Composite

    Decorator

    Flyweight

    Facade

    Proxy

    Interpreter

    Template Method

    Chain of

    ResponsibilityCommand

    Iterator

    Mediator

    Memento

    Observer

    State

    Strategy

    Visitor

    E.

    Gamma,R.Helm,R.Johnson,J

    .VlissidesandAddison-Wesley

  • 8/2/2019 Dpatterns Overview Examples

    8/81

    Observer (Behavioral)

    Intent

    Define a one-to-many dependency between objects so that

    when one object changes state, all its dependents are notified

    and updated automatically

    Applicability When an abstraction has two aspects, one dependent on the

    other

    When a change to one object requires changing others, and you

    don't know how many objects need to be changed

    When an object should notify other objects without making

    assumptions about who these objects are

    E.

    Gamma,R.Helm,R.Johnson,J.VlissidesandAddison-Wesley

  • 8/2/2019 Dpatterns Overview Examples

    9/81

    Observer (Cont'd)

    Structure

    +attach(in o : Observer)+detach(in o : Observer)+notify()

    Subject

    +update()

    Observer

    +getState()

    -subjectState

    ConcreteSubject

    +update()

    -observerState

    ConcreteObserver

    1

    -observers

    *

    {observerState =

    subject.getState() }{return subjectState }

    {for all o in observers

    { o.update() } }

    -subject

    1 *

    E.

    Gamma,R.Helm,R.Johnson,J.VlissidesandAddison-Wesley

  • 8/2/2019 Dpatterns Overview Examples

    10/81

    Observer (Cont'd)

    Consequences+ Modularity: subject and observers may vary independently

    + Extensibility: can define and add any number of observers

    + Customizability: different observers provide different views of

    subject Unexpected updates: observers don't know about each other

    Update overhead: might need hints

    Implementation Subject-observer mapping

    Dangling references Avoiding observer-specific update protocols: the push and

    push/pull models

    Registering modifications of interest explicitly

    E.

    Gamma,R.Helm,R.Johnson,J.VlissidesandAddison-Wesley

  • 8/2/2019 Dpatterns Overview Examples

    11/81

    Observer (Cont'd)

    Known uses

    Smalltalk model-view-controller (MVC)

    Interviews (subjects and views)

    Andrew (data objects and views)

    Benefits

    Design reuse

    Uniform design vocabulary

    Enhance understanding, restructuring

    Basis for automation

    E.Gamma,R.Helm,R.Johnson,J.VlissidesandAddison-Wesley

  • 8/2/2019 Dpatterns Overview Examples

    12/81

  • 8/2/2019 Dpatterns Overview Examples

    13/81

    Schematic Observer Example

    Subject

    Observers

  • 8/2/2019 Dpatterns Overview Examples

    14/81

    Observer - Sample Code

    class Subject {public:

    virtual ~Subject();virtual void Attach(Observer*);virtual void Detach(Observer*);virtual void Notify();

    protected:Subject();

    private:List *_observers;

    };

    void Subject::Attach (Observer* o) {_observers->Insert(_observers->end(),

    o);}

    void Subject::Detach (Observer* o) {_observers->remove(o);}

    void Subject::Notify () {ListIteratori(_observers);

    for (i.First(); !i.IsDone(); i.Next()) {i.CurrentItem()->Update(this);

    }}

    class Observer {

    public:

    virtual ~Observer();

    virtual void Update(Subject* theChangeSubject) = 0;

    protected:

    Observer();

    };

    class ClockTimer : public Subject {

    public:

    ClockTimer();

    virtual int GetHour();

    virtual int GetMinute();

    virtual int GetSecond();void Tick();

    };

    void ClockTimer::Tick() {

    // update internal time-keeping state

    // ...

    Notify();

    }

  • 8/2/2019 Dpatterns Overview Examples

    15/81

  • 8/2/2019 Dpatterns Overview Examples

    16/81

    Overview

    Motivation and Concept

    Observer

    Example: WYSIWYG Editor Composite

    Strategy

    Decorator

    Abstract Factory

  • 8/2/2019 Dpatterns Overview Examples

    17/81

  • 8/2/2019 Dpatterns Overview Examples

    18/81

    Composite (Cont'd)

    Structure

    +operation()

    +add(in c : Component)

    +remove(in c : Component)

    +getChild(in i : int)

    Component

    +operation()

    Leaf

    1

    -children

    *

    +operation()

    +add(in c : Composite)

    +remove(in c : Composite)

    +getChild(in i : int)

    Composite

    { forall g in children

    g.operation(); }

    E.Gamma,R.Helm,R.Johnson,J.VlissidesandAddison-Wesley

  • 8/2/2019 Dpatterns Overview Examples

    19/81

    Composite (Cont'd)

    Consequences+ Uniformity: treat components the same regardless of

    complexity

    + Extensibility: new Component subclasses workwherever old ones do

    Overhead: might need prohibitive numbers of objects

    Implementation Do Components know their parents?

    Uniform interface for both leaves and composites?

    Don't allocate storage for children in Component baseclass

    Responsibility for deleting children

    E.Gamma,R.Helm,R.Johnson,J.VlissidesandAddison-Wesley

  • 8/2/2019 Dpatterns Overview Examples

    20/81

    Composite (Cont'd)

    Known Uses

    ET++ VObjects

    InterViews Glyphs, Styles

    Unidraw Components, MacroCommands

    E.Gamma,R.Helm,R.Johnson,J.VlissidesandAddison-Wesley

  • 8/2/2019 Dpatterns Overview Examples

    21/81

    Composite - Example

  • 8/2/2019 Dpatterns Overview Examples

    22/81

  • 8/2/2019 Dpatterns Overview Examples

    23/81

    Strategy (Behavioral)

    Intent Define a family of algorithms, encapsulate

    each one, and make them interchangeable to

    let clients and algorithms vary independently Applicability

    When an object should be configurable withone of several algorithms,

    andall algorithms can be encapsulated,andone interface covers all encapsulations

    E.Gamma,R.Helm,R.Johnson,J.VlissidesandAddison-Wesley

  • 8/2/2019 Dpatterns Overview Examples

    24/81

    Strategy (Cont'd)

    Structure

    +contextInterface()

    Context (Composition)

    +algorithmInterface()

    Strategy (Compositor)

    +algorithmInterface()

    ConcreteStrategyA

    +algorithmInterface()

    ConcreteStrategyB

    +algorithmInterface()

    ConcreteStrategyC

    1 1

    E.Gamma,R.Helm,R.Johnson,

    J.VlissidesandAddison-Wesley

  • 8/2/2019 Dpatterns Overview Examples

    25/81

    Strategy (Cont'd)

    Consequences+ Greater flexibility, reuse

    + Can change algorithms dynamically

    Strategy creation & communication overhead

    Inflexible strategy interface Implementation

    Exchanging information between a strategy and its context

    Static strategy selection via templates

    Known uses Interviews text formatting

    RTL register allocation & scheduling strategies

    Et++SwapsManager calculation engines

    E.Gamma,R.Helm,R.Johnson,

    J.VlissidesandAddison-Wesley

  • 8/2/2019 Dpatterns Overview Examples

    26/81

  • 8/2/2019 Dpatterns Overview Examples

    27/81

  • 8/2/2019 Dpatterns Overview Examples

    28/81

    Strategy Sample Code

    template

    void DecreasePrint::doAlgorithm(T* const cont){

    for (int i=0; iarray[i];

    quicksortD(array, 0, 9);::printf("DECREASING ORDER\n");

    for (int i=0; idoAlgorithm((T *)this);

    }

    else

    {::printf("Error: there is no strategy attached to the context\n");

    ::printf("An exeception has been thrown\n");

    throw "Error: there is no stategy attach to the context";

    }

    }

    void Context::attachStrategy(Strategy * anotherStrategy){

    if (aggregation)delete thisStrategy;

    thisStrategy = anotherStrategy;

    }

  • 8/2/2019 Dpatterns Overview Examples

    29/81

  • 8/2/2019 Dpatterns Overview Examples

    30/81

    Strategy Sample Codemain(int argc, char **argv){

    ConcreteContext * context1 = new ConcreteContext();

    context1->attachStrategy((Strategy *)(new Print()));

    context1->execute();

    ::printf("*****************\n");

    ConcreteContext * context2 = new ConcreteContext(*context1); // Copy constructor

    context1->attachStrategy((Strategy *)(new IncreasePrint()));

    context1->execute();

    ::printf("*****************\n");

    context1->removeStrategy();

    context1->attachStrategy((Strategy *)(new DecreasePrint()));context1->execute();

    context1->removeStrategy();

    delete context1;

    ::printf("*****Context2******\n");

    context2->execute();

    context2->removeStrategy();

    delete context2;

    :: printf("\n Testing Aggregation \n\n");

    context1 = new ConcreteContext( (Strategy *)(new IncreasePrint()));

    context1->execute();

    ::printf("*****************\n");

    context2 = new ConcreteContext(*context1);

    delete context1;

    context2->execute();

    delete context2;}

  • 8/2/2019 Dpatterns Overview Examples

    31/81

    Decorator (Structural)

    Intent

    Augment objects with new responsibilities

    Applicability

    When extension by subclassing is impractical

    For responsibilities that can be withdrawn

    E

    .Gamma,R.Helm,R.Johnson,

    J.VlissidesandAddison-Wesley

  • 8/2/2019 Dpatterns Overview Examples

    32/81

    Decorator Diagram

    Structure

    E

    .Gamma,R.Helm,R.Johnson,

    J.VlissidesandAddison-Wesley

    +operation()

    Component (Glyph)

    +operation()

    ConcreteComponent

    +operation()

    Decorator (MonoGlyph)

    +operation()

    -addedState

    ConcreteDecoratorA

    +operation()

    +addedBehavior()

    ConcreteDecoratorB

    1

    -component

    1

    { component-> component.operation(); }

    { super.operation();

    addedBehavior(); }

  • 8/2/2019 Dpatterns Overview Examples

    33/81

  • 8/2/2019 Dpatterns Overview Examples

    34/81

  • 8/2/2019 Dpatterns Overview Examples

    35/81

    Decorator Comments The Decorator pattern gives you a lot of flexibility,

    since you can change what the decorator does atruntime, as opposed to having the change be staticand determined at compile time by subclassing.

    Since a Decorator complies with the interface that theobject that it contains, the Decorator isindistinguishable from the object that it contains. Thatis, a Decorator is a concrete instance of the abstractclass, and thus is indistinguishable from any otherconcrete instance, including other decorators.

    This can be used to great advantage, as you canrecursively nest decorators without any other objectsbeing able to tell the difference, allowing a near infiniteamount of customization.

  • 8/2/2019 Dpatterns Overview Examples

    36/81

    Decorator (Cont'd)

    Consequences+ Responsibilities can be added/removed at run-time

    +Avoids subclass explosion

    + Recursive nesting allows multiple responsibilities

    Interface occlusion

    Identity crisis

    Implementation

    Interface conformance Use a lightweight, abstract base class for Decorator

    Heavyweight base classes make Strategy moreattractive

    E

    .Gamma,R.Helm,R.Johnson,

    J.VlissidesandAddison-Wesle

    y

  • 8/2/2019 Dpatterns Overview Examples

    37/81

  • 8/2/2019 Dpatterns Overview Examples

    38/81

    Decorator Example

  • 8/2/2019 Dpatterns Overview Examples

    39/81

  • 8/2/2019 Dpatterns Overview Examples

    40/81

    Decorator Example

    abstract class Decorator extends LibItem{ LibItem item;

    public Decorator(LibItem li) {

    item = li;

    }

    public String getTitle() {

    return item.getTitle();

    }// Following methods are

    // similarly implemented

    public String getAuthor() {...

    public intgetCopies() { ...

    public intcopiesOnShelf() { ...

    public void decCopiesOnShelf() {

    item.decCopiesOnShelf();

    }// and similarly...

    public void incCopiesOnShelf() {...

  • 8/2/2019 Dpatterns Overview Examples

    41/81

    Decorator Example

  • 8/2/2019 Dpatterns Overview Examples

    42/81

    Decorator Example - (client)// Non borrowable, non reservablebook

    LibItem b1 = new Book("A", "B", 1);

    // BorrowablevideoLibItem v1 = new BorrowableDec(new Video("V", 3));

    // borrow unborrowableitem -copies should stay 1

    b1.borrowItem("Bob");

    System.out.println("Copiesof book = " +b1.copiesOnShelf());

    // borrow video -copies decremented to 2

    v1.borrowItem("Fred");

    System.out.println("Copiesof video = " +v1.copiesOnShelf());

    //make book borrowableand borrow it -copies = 0

    LibItem b2 = new BorrowableDec(b1);

    b2.borrowItem("Bob");

    System.out.println("Copiesof book = " +b2.copiesOnShelf());

    // make book reservable

    LibItem b3 = new ReservableDec(b2);

    b3.reserve("Alice");

    b3.returnItem("Bob");// book returned -back to 1 copy

    System.out.println("Copiesof book = " +b3.copiesOnShelf());

    // Not reserved for Jane -still 1 copy

    b3.borrowItem("Jane");

    System.out.println("Copiesof book = " +b3.copiesOnShelf());

    // Okay Alice can borrow -down to 0

    b3.borrowItem("Alice");

    System.out.println("Copiesof book = " +b3.copiesOnShelf());

  • 8/2/2019 Dpatterns Overview Examples

    43/81

  • 8/2/2019 Dpatterns Overview Examples

    44/81

    Abstract Factory (Cont'd)

    Structure

    +createProductA()

    +createProductB()

    AbstractFactory

    AbstractProductB+createProductA()

    +createProductB()

    ConcreteFactory1

    +createProductA()

    +createProductB()

    ConcreteFactory2

    ProductB1 ProductB2

    AbstractProductA

    ProductA1 ProductA2

    Client

    * *

    *

    *

    *

    *

    instantiateinstantiate

    instantiate

    instantiate

    E

    .Gamma,R.Helm,R.Johnson,J.VlissidesandAddison-Wesle

    y

  • 8/2/2019 Dpatterns Overview Examples

    45/81

    Abstract Factory - Example

    public class MazeFactory {

    public MazeFactory() {...}

    public Maze makeMaze(){

    return new Maze();

    }

    public Room makeRoom(int n) {return new Room(n);

    }

    public Wall makeWall() {

    return new Wall();

    }

    public Door makeDoor(Room r1, Roomr2) {

    return new Door(r1, r2);

    }

    };

    public class MazeGame {

    // ...

    public Maze createMaze (MazeFactory factory) {

    Maze aMaze = factory.makeMaze();

    Room r1 = factory.makeRoom(1);

    Room r2 = factory.makeRoom(2);Door theDoor = factory.makeDoor(r1, r2);

    aMaze.addRoom(r1);

    aMaze.addRoom(r2);

    r1.setSide(MapSite.NORTH, factory.makeWall());

    r1.setSide(MapSite.EAST, theDoor);

    r1.setSide(MapSite.SOUTH, factory.makeWall());

    r1.setSide(MapSite.WEST, factory.makeWall());

    r2.setSide(MapSite.NORTH, factory.makeWall());

    r2.setSide(MapSite.EAST, factory.makeWall());

    r2.setSide(MapSite.SOUTH, factory.makeWall();

    r2.setSide(MapSite.WEST, theDoor); return aMaze;

    }

    }

  • 8/2/2019 Dpatterns Overview Examples

    46/81

    Abstract Factory - Example

    public class EnchantedMazeFactory extends MazeFactory {

    public EnchantedMazeFactory() {...}public Room makeRoom(int n) {

    return new EnchantedRoom(n, new Spell());

    }

    public Door makeDoor(Room r1, Room r2) {

    return new DoorNeedingSpell(r1, r2);

    }}

    public class BombedMazeFactory extends MazeFactory {public BombedMazeFactory() {...}

    public Wall makeWall(){

    return new BombedWall();}

    public Room makeRoom(int n){

    return new RoomWithABomb(n);

    }

    }

  • 8/2/2019 Dpatterns Overview Examples

    47/81

    Abstract Factory - Client

    MazeGame game; // The instance of a game..

    Maze aMaze; // A reference to a maze.

    switch(choice) {case ENCHANTED: {

    EnchantedMazeFactory factory = new EnchantedMazeFactory();aMaze = game.createMaze(factory);break;

    }case BOMBED: {

    BombedMazeFactory factory = new BombedMazeFactory();aMaze = game.createMaze(factory);

    break;}

    }

  • 8/2/2019 Dpatterns Overview Examples

    48/81

  • 8/2/2019 Dpatterns Overview Examples

    49/81

  • 8/2/2019 Dpatterns Overview Examples

    50/81

    Iterator (Behavioral)

    Intent

    Access elements of an aggregate sequentially without

    exposing its representation

    Applicability Require multiple traversal algorithms over an

    aggregate

    Require a uniform traversal interface over different

    aggregates When aggregate classes and traversal algorithm must

    vary independently

    E.Gamma,R.Helm,R.Johnson,J.VlissidesandAddison-Wesley

  • 8/2/2019 Dpatterns Overview Examples

    51/81

    Iterator (cont'd)

    Structure

    +createIterator()

    Aggregate (Glyph)

    +first()

    +next()+isDone()

    +currentItem()

    Iterator

    Client

    +createIterator()

    ConcreteAgregate ConcreteIterator

    { return ConcreteIterator(this); }

    1 *

    * * * *

    E.Gamma,R.Helm,R.Johnson,J.VlissidesandAddison-Wesley

  • 8/2/2019 Dpatterns Overview Examples

    52/81

  • 8/2/2019 Dpatterns Overview Examples

    53/81

    Iterator Example

    class IteratorDemo {public static void main( String[] args ) {

    IntSet set = new IntSet();

    . // Code to add elements to the set and other code

    // Clients ask the collection object to create many iterator objects

    IntSet.Iterator it1 = set.createIterator();

    IntSet.Iterator it2 = set.createIterator();

    // Clients use the first(), isDone(), next(), currentItem() protocol

    System.out.print( "\nIterator: " );

    for ( it1.first(), it2.first(); ! it1.isDone(); it1.next(), it2.next() )

    System.out.print( it1.currentItem() + " " + it2.currentItem() + " " );

    System.out.print( "\nEnumeration: " );for (Enumeration e = set.getHashtable().keys(); e.hasMoreElements(); )

    System.out.print( e.nextElement() + " " );

    System.out.println();

    }

    }

  • 8/2/2019 Dpatterns Overview Examples

    54/81

  • 8/2/2019 Dpatterns Overview Examples

    55/81

    Overview

    Example: WYSIWYG Editor (Cont'd) Spelling checking & hyphenation

    Iterator

    Visitor

    Some more patterns Template Method

    Singleton

    Faade

    Observations and Conclusions

    Further reading

  • 8/2/2019 Dpatterns Overview Examples

    56/81

    Visitor (Behavioral)

    Intent Centralize operations on an object structure so that

    they can vary independently but still behavepolymorphically

    Applicability When classes define many unrelated operations

    Class relationships of objects in the structure rarelychange, but the operations on them change often

    Algorithms over the structure maintain state that'supdated during traversal

    E.Gamma,R.Helm,R.Johnson

    ,J.VlissidesandAddison-Wesley

  • 8/2/2019 Dpatterns Overview Examples

    57/81

  • 8/2/2019 Dpatterns Overview Examples

    58/81

    Visitor (cont'd)

    Consequences+ Flexibility: visitor and object structure are independent

    + Localized functionality

    Circular dependency between Visitor and Element interfaces

    Visitor brittle to new ConcreteElement classes

    Implementation Double dispatch

    Overloading visit operations

    Catch-all operation

    General interface to elements of object structure Known Uses

    ProgramNodeEnumerator in Smalltalk-80 compiler

    IRIS Inventor scene rendering

    E.Gamma,R.Helm,R.Johnson

    ,J.VlissidesandAddison-Wesley

  • 8/2/2019 Dpatterns Overview Examples

    59/81

  • 8/2/2019 Dpatterns Overview Examples

    60/81

    Editor Example Summary

    Document Structure Composite

    Formatting Strategy

    Embellishment

    Decorator

    Multiple Look&Feels Abstract Factory

    (Multiple window systems) Bridge

    (User operations) Command

    Spelling checking & hyphenation Iterator & Visitor

  • 8/2/2019 Dpatterns Overview Examples

    61/81

    Overview

    Example: WYSIWYG Editor (Cont'd) Spelling checking & hyphenation

    Iterator

    Visitor

    Some more patterns Template Method

    Singleton

    Faade

    Observations and Conclusions

    Further reading

  • 8/2/2019 Dpatterns Overview Examples

    62/81

    Template Method (Behavioral)

    Intent Define the skeleton of an algorithm in an

    operation, deferring some steps to subclasses

    Applicability To implement invariant aspects of an

    algorithm once and let subclasses definevariant parts

    To localize common behavior in a class toincrease code reuse

    To control subclass extensions

    E.Gamma,R.Helm,R.Johnson

    ,J.VlissidesandAddison-Wesl

    ey

  • 8/2/2019 Dpatterns Overview Examples

    63/81

    Template Method (cont'd)

    Structure

    +templateMethod()

    +primitiveOperation1()

    +primitiveOperation2()

    AbstractClass{...

    primitiveOperation1();...

    primitiveOperation2();

    ...}

    +primitiveOperation1()

    +primitiveOperation2()

    ConcreteClass

    E.Gamma,R.Helm,R.Johnson

    ,J.VlissidesandAddison-Wesley

  • 8/2/2019 Dpatterns Overview Examples

    64/81

    Template Method (cont'd)

    Consequences+ Leads to inversion of control (Hollywood principle: don't call us

    we'll call you)

    + Promotes code reuse

    + Lets you enforce overriding rules

    Must subclass to specialize behavior

    Implementation Virtual vs. non-virtual template method

    Few vs. lots of primitive operations

    Naming conventions (do- prefix) Known Uses

    Just about all object-oriented systems (especially frameworks)

    E.Gamma,R.Helm,R.Johnson

    ,J.VlissidesandAddison-Wesley

  • 8/2/2019 Dpatterns Overview Examples

    65/81

    Template Method (cont'd)

    Typical implementation:public abstract class Node {

    public final void streamOut (OutputStream out) {

    if (isReadable()) {

    doStreamOut(out);

    } else {

    doWarning(unreadableWarning);

    }

    }

    // ...

    isReadable, doStreamOut, and doWarningare primitive operations

    E.Gamma,R.Helm,R.Johnson

    ,J.VlissidesandAddison-Wesley

  • 8/2/2019 Dpatterns Overview Examples

    66/81

    Template Methid - Example

  • 8/2/2019 Dpatterns Overview Examples

    67/81

    Template Method - Example

    class Account{public:

    void Transaction(float amount);void virtual TransactionSubpartA();

    void virtual TransactionSubpartB();

    void virtual TransactionSubpartC();

    }

    void Account::Transaction(float amount){TransactionSubpartA();TransactionSubpartB();TransactionSubpartC();// EvenMoreCode;}

    class JuniorAccount : public Account

    {

    public:

    void virtual TransactionSubpartA();

    }

    class SavingsAccount : public Account

    {

    public:

    void virtual TransactionSubpartC();

    }

    // Client code

    Account* customer;

    customer = createNewAccount();

    customer->Transaction(amount);

  • 8/2/2019 Dpatterns Overview Examples

    68/81

    Singleton (Creational)

    Intent

    Ensure a class only ever has one instance, and

    provide a global point of access to it.

    Applicability When there must be exactly one instance of a class,

    and it must be accessible from a well-known access

    point

    When the sole instance should be extensible bysubclassing, and clients should be able to use an

    extended instance without modifying their code

    E.Gamma,R.Helm,R.Johnson,J.VlissidesandAddison-Wesley

  • 8/2/2019 Dpatterns Overview Examples

    69/81

    Singleton (cont'd)

    Structure

    +instance()

    +singletonOperation()

    +getSingletonData()

    -uniqueInstance : Singleton

    -singletonData

    Singleton

    { return uniqueInstance; }

    E.Gamma,R.Helm,R.Johnson,J.VlissidesandAddison-Wesley

  • 8/2/2019 Dpatterns Overview Examples

    70/81

    Singleton (cont'd)

    Consequences+ Reduces namespace pollution

    + Makes it easy to change your mind and allow morethan one instance

    +Allow extension by subclassing Same drawbacks of a global if misused

    Implementation may be less efficient than a global

    Concurrency pitfalls

    Implementation Static instance operation

    Registering the singleton instance

    E.Gamma,R.Helm,R.Johnson,J.VlissidesandAddison-Wesley

  • 8/2/2019 Dpatterns Overview Examples

    71/81

    Singleton (cont'd)

    Known Uses

    Unidraw's Unidraw object

    Smalltalk-80 ChangeSet, the set of changes

    to code InterViews Session object

    E.Gamma,R.Helm,R.Johnson,J.VlissidesandAddison-Wesley

  • 8/2/2019 Dpatterns Overview Examples

    72/81

    Singleton - Example

    class Singleton {

    public:

    static Singleton* Instance();

    protected:

    Singleton();Singleton(const Singleton&);

    Singleton& operator= (const Singleton&)

    private:

    static Singleton* pinstance;

    };

    Singleton* Singleton::pinstance = 0;

    // initialize pointer

    Singleton* Singleton::Instance () {

    if (pinstance == 0) // is it the first call? {

    pinstance = new Singleton;// create sole instance

    }

    return pinstance;

    // address of sole instance

    }

    Singleton::Singleton() {

    //... perform necessary instance initializations

    }

  • 8/2/2019 Dpatterns Overview Examples

    73/81

    Singleton - Example

    // Client code

    Singleton *p1 = Singleton::Instance();

    Singleton *p2 = p1->Instance();

    Singleton & ref = * Singleton::Instance();

    Although the above example uses a single instance,

    modifications to the function Instance() may permit

    a variable number of instances. For example, youcan design a class that allows up to three instances.

  • 8/2/2019 Dpatterns Overview Examples

    74/81

    Overview

    Example: WYSIWYG Editor (Cont'd) Spelling checking & hyphenation

    Iterator

    Visitor

    Some more patterns Template Method

    Singleton

    Faade

    Observations and Conclusions

    Further reading

  • 8/2/2019 Dpatterns Overview Examples

    75/81

    Faade

    Faade

    E.Gamma,R.Helm,R.Johnson,J.VlissidesandAddison-Wesley

    Faade

  • 8/2/2019 Dpatterns Overview Examples

    76/81

    Faade

  • 8/2/2019 Dpatterns Overview Examples

    77/81

    Faade - Example

  • 8/2/2019 Dpatterns Overview Examples

    78/81

  • 8/2/2019 Dpatterns Overview Examples

    79/81

    Ob i

  • 8/2/2019 Dpatterns Overview Examples

    80/81

    Observations

    Patterns permit design at a more abstract level Treat many class/object interactions as a unit

    Often beneficial after initial design

    Targets for class refactorings Variation-oriented design

    Consider what design aspects are variable

    Identify applicable pattern(s)

    Vary patterns to evaluate tradeoffs

    Repeat

    (D i ) P R f

  • 8/2/2019 Dpatterns Overview Examples

    81/81

    (Design) Pattern References

    The Timeless Way of Building, Alexander; Oxford, 1979; ISBN 0-19-502402-8

    A Pattern Language, Alexander; Oxford, 1977; ISBN 0-19-501-919-9

    Design Patterns, Gamma, et al.; Addison-Wesley, 1995; ISBN 0-

    201-63361-2; CD version ISBN 0-201-63498-8 Pattern-Oriented Software Architecture, Buschmann, et al.; Wiley,

    1996; ISBN 0-471-95869-7

    Analysis Patterns, Fowler; Addison-Wesley, 1996; ISBN 0-201-89542-0

    Smalltalk Best Practice Patterns, Beck; Prentice Hall, 1997; ISBN 0-13-476904-X

    The Design Patterns Smalltalk Companion, Alpert, et al.; Addison-Wesley, 1998; ISBN 0-201-18462-1

    AntiPatterns, Brown, et al.; Wiley, 1998; ISBN 0-471-19713-0