CIS-75 Home http://www.c-jump.com/CIS75/CIS75syllabus.htm

Design Patterns


  1. Design Pattern C++ Samples
  2. Creational Patterns
  3. Abstract Factory
  4. Abstract Factory Requirements
  5. Abstract Maze Factory Sample
  6. Abstract Maze Factory Sample, cont.
  7. Abstract Factory UML Example
  8. Abstract Factory Benefits
  9. Abstract Factory Structure
  10. Builder
  11. Builder Sample I, Maze Game
  12. Builder Sample II, Pizza Restaurant
  13. Difference between Builder and Factory Pattern
  14. Factory Method
  15. Prototype
  16. Prototype Structure
  17. Prototype Sample
  18. Singleton
  19. Singleton Collaboration with Clients
  20. Singleton Implementation Considerations
  21. Singleton Sample
  22. Singleton Related Patterns
  23. Structural Patterns
  24. Adapter
  25. Adapter UML Diagram
  26. Adapter Sample
  27. Adapter Implementation
  28. Abstract Adapter
  29. Bridge
  30. Bridge Sample
  31. Composite
  32. Composite UML Diagram
  33. Composite Sample
  34. Composite Benefits and Disadvantages
  35. Decorator
  36. Decorator Sample
  37. Decorator Sample, cont.
  38. Decorator Benefits and Disadvantages
  39. Facade
  40. Proxy
  41. Proxy UML
  42. Proxy Collaboration
  43. Proxy Types
  44. Virtual Proxy Sample
  45. Proxy Benefits
  46. Discussion of Structural Patterns
  47. Discussion of Structural Patterns, cont.
  48. Behavioral Patterns
  49. Command
  50. Command Sample
  51. Command Sample, cont.
  52. Iterator
  53. Iterator Structure
  54. Iterator Sample
  55. Null Iterator
  56. Iterator Summary
  57. Memento
  58. Memento Structure
  59. Memento Implementation
  60. Observer
  61. Observer Structure
  62. Observer Usage
  63. Observer Sample
  64. Observer Sample, cont.
  65. Visitor
  66. Visitor, cont.
  67. Visitor Structure
  68. Visitor Benefits
  69. Visitor Sample
  70. Patterns and You
  71. Conclusion

1. Design Pattern C++ Samples

Creational Structural Behavioral

2. Creational Patterns



3. Abstract Factory



4. Abstract Factory Requirements


  1. Client must use an abstract interface, known as abstract factory to manufacture instances of object supply.

  2. Client must also use an abstract interface to access object supply.

     

     


5. Abstract Maze Factory Sample


  • Consider a Maze Game ( download ), which needs a supply of

    • Walls

    • Doors

    • Rooms

    to construct a Maze.

    Maze Class Relationships

6. Abstract Maze Factory Sample, cont.



7. Abstract Factory UML Example



8. Abstract Factory Benefits



9. Abstract Factory Structure



10. Builder



11. Builder Sample I, Maze Game


  • The Builder ( download ) sample is the successor of the Maze Game application:

  • MazeGame is the director object with CreateMaze() operation to build complex Maze object from a specific configuration.

  • StandardMazeBuilder and CountingMazeBuilder are concrete builders.

  • The StandardMazeBuilder constructs individual Rooms and other parts of the Maze.

    Maze Game Builder Sample

12. Builder Sample II, Pizza Restaurant


  • The BuilderPizza ( download ) sample is a Pizza Restaurant application:

    • Waiter is a director object with ConstructPizza() operation to build configuration-based Pizzas.

    • The HawaiianPizzaBuilder and SpicyPizzaBuilder are concrete builders.

    BuilderPizza Sample

13. Difference between Builder and Factory Pattern

  • Abstract Factory Pattern:

  • Emphasises object creation operations for families of related objects,

    • where each family is a set classes derived from a common base.

  • Each object is returned immediately as a result of one call.

  • Builder pattern:

  • Focuses on constructing a complex object
    step by step.

  • Formulates the logic of how to put together a complex object:

    • Builder object encapsulates configuration of the complex object.

    • Director object knows the protocol of using the Builder,

      • where the protocol defines all logical steps required to build the complex object.


14. Factory Method


    factory method for making pizza
  • Static operation PizzaFactory::create_pizza( )
    takes "pizza ID" strings,

    • "Default"

    • "Ham and Mushroom"

    • "Hawaiian"

    and creates a corresponding object.


15. Prototype


  • Any subclass that needs a polymorphic constructor capability,

    1. Derives itself from the abstract base class

    2. Implements the clone( ) operation.

  • The client has two options under this design:

    • Call a factory method, providing prototypical instance as a parameter

    • Invoke some another action that calls the prototype's clone( ) operation.


16. Prototype Structure



17. Prototype Sample


  • The Prototype ( download ) sample illustrates a "record system" for cars, bikes, and people.

  • The RecordFactory class creates necessary prototypical instances of Records.

  • Each record type implements the clone( ) operation to manufacture exact copies.

    Prototype Sample

18. Singleton



19. Singleton Collaboration with Clients

  • Clients should access a Singleton instance solely through Singleton::GetInstance( ) operation:

      Singleton collaboration with clients

  • Singleton UML class diagram:

      Singleton UML class diagram


20. Singleton Implementation Considerations


  1. If instance of the class does not exist, the new instance is created.

  2. If an instance already exists, Singleton simply returns a reference to that object.

  3. The singleton pattern must be carefully constructed in multi-threaded applications:

     


21. Singleton Sample



22. Singleton Related Patterns



23. Structural Patterns



24. Adapter



25. Adapter UML Diagram



26. Adapter Sample



27. Adapter Implementation



28. Abstract Adapter



29. Bridge



30. Bridge Sample


  • Consider the abstraction of shapes.

  • The interface named DrawingAPI could be implemented by concrete classes, DrawingAPI1 or DrawingAPI2.

  • The client instantiates drawing primitives CircleShape:

      Bridge patern UML Hierarchy diagram

  • The Bridge design pattern bridges two hierarchies via CircleShape collaboration:

      Bridge patern UML Collaboration diagram

  • Instances of CircleShape will forward drawing requests to either DrawingAPI1 or DrawingAPI2.


31. Composite



32. Composite UML Diagram


    Composite UML Class Diagram
  • Component declares the interface for objects in the composition.

  • If necessary, Component implements default behavior common to all classes.

  • Leaf represents leaf (terminal) objects in the composition.

  • Composite represents a component with children, a tree branch.

  • Composite also implements methods to manipulate children.


33. Composite Sample



34. Composite Benefits and Disadvantages



35. Decorator


    Text view example
  • Word processing application

  • The application displays text in a window.

  • If the text fits into the view, the window has no scroll bars.

  • Otherwise, scroll bars are added to the view.

  • Additional window decorations may be required, such as a border with particular thickness.

     

  • How could we add dynamic view functionality to our design?


36. Decorator Sample


    Decorator UML Class Diagram
  • VisualComponent is the abstract class for all visual objects with interface for drawing and event handling, such as Resize( ).

  • TextView::Draw( ) displays text in the window.

  • ScrollDecorator adds scroll bars to the view, if necessary.

  • BorderDecorator adds the window border.


37. Decorator Sample, cont.


    Decorator UML Class Diagram
  • The Decorator maintains reference to the VisualComponent, and serves as a node of a singly-linked list of all visual components.

  • The BorderDecorator and ScrollDecorator are Concrete Decorators, which

    1. Add extra responsibilities to the visual component

    2. Forward requests to the abstract Decorator. The Decorator class further communicates window requests (such as Draw and Resize) to the next visual component on Decorator's list.


38. Decorator Benefits and Disadvantages



39. Facade



40. Proxy



41. Proxy UML



42. Proxy Collaboration



43. Proxy Types



44. Virtual Proxy Sample


  • The Proxy ( download ) example illustrates implementation of the virtual proxy pattern.

  • The ProxyImage class delays the expensive operation of loading the image file from disk until the operation is actually requested by the client.

  • If the file is never needed, the expensive loading step is completely eliminated.

    Virtual Proxy Design

45. Proxy Benefits



46. Discussion of Structural Patterns



47. Discussion of Structural Patterns, cont.



48. Behavioral Patterns



49. Command



50. Command Sample

  • Command Pattern Generic UML Design:

      Command Pattern UML Design

  • The Command ( download ) sample demonstrates command-style food preparation:

      Command Hierarchy

  • CmdStack class represents a queue with capabilities of

    • add command

    • undo command

    • createRecipe action


51. Command Sample, cont.

  • Command Pattern Generic UML Design:

      Command Pattern UML Design

    Command Hierarchy
  • The main( ) function is the Invoker.

  • The standard output is the Receiver.

  • Command class is an interface to the concrete commands with abstract execute( ) operation.

  • The Ingredient and Step are concrete commands implementing the execute( ) operation.


52. Iterator



53. Iterator Structure


  • Solution:

      Iterator UML Class Diagram

  • Aggregate defines an interface for creating an Iterator object.

  • ConcreteAggregate implements the Iterator creation and returns instance of the proper ConcreteIterator.

  • Iterator defines an interface for element traversal and access.

  • ConcreteIterator implements the Iterator interface.

  • ConcreteIterator keeps track of the current position in the traversal of the aggregate.


54. Iterator Sample


  • The Iterator ( download ) sample illustrates a set of Object instances aggregated within ObjectCollection.

  • The Iterator design implements traversal of Objects by a CollectionIterator.

  • The algorithm uses CollectionIterator to access each Object instance and invokes Object::Print() operation to display object IDs.

    Iterator Sample

55. Null Iterator



56. Iterator Summary



57. Memento



58. Memento Structure


  • Solution: Memento UML Class Diagram

  • Memento stores internal state of the Originator object.

  • Originator creates a Memento containing a snapshot of its current internal state.


59. Memento Implementation

  • 
    class Memento {
    public:
        virtual ~Memento();
    
    private:
        friend class Item;
        Memento();
        //...
    };//class Memento
    
    class Item {
    public:
        Memento* create_memento();
        void restore_memento( Memento* );
        //...
    };//class Item
    
    
  • Class Item is the originator with some internal states.

  • The user of Item::create_memento( ) and Item::restore_memento( ) is commonly referred to as a caretaker.

  • We usually want Memento objects be created only by Item::create_memento( ).

  • We might also want to allow incremental restoration via a stack of Mementos.

  • It is possible to implement Memento file I/O (or database) interface to add persistence of states.


60. Observer



61. Observer Structure


    Observer UML Class Diagram
  • Subject is an abstract class that provides an interface for attaching and detaching Observers.

  • Subject::Notify operation notifies each Observer by calling Observer::Update operation, known as raising the state change event.

  • Observer is the interface for all observers who receive notifications from the Subject.


62. Observer Usage



63. Observer Sample


  • The Observer ( download ) sample illustrates the Observer design pattern as follows:

  • WeatherDataInterface defines the subject interface to register, remove, and notify the observers.

    Observer Sample

64. Observer Sample, cont.


  • When ParaWeatherData subject issues weather update notification, the state change event is communicated via two calls:

    • ObserverBoardInterface::update( humidity, temperature, pressure )

    • DisplayBoardInterface::show()

    Observer Sample

65. Visitor



66. Visitor, cont.



67. Visitor Structure


    Visitor UML Class Diagram
  • The Visitor can visit objects that don't have a common parent class.

  • Although the ConcreteElement nodes may represent unrelated classes, they all should derive from a common Element base.

  • The client instantiates a ConcreteVisitor.

  • The traversal algorithm invokes Element::accept(Visitor) for each node.

  • The ConcreteElement calls Visitor::visit(ConcreteElement).

  • The ConcreteVisitor now uses the ConcreteElement interface to carry out node-specific tasks.

68. Visitor Benefits



69. Visitor Sample


  • The Visitor ( download ) sample illustrates this design pattern as follows:

    • Car is a complex object with Body, Engine, and Wheel parts, all derived from the CarElement base.

    • CarElementVisitor is an abstract visitor interface, declaring operations to visit Body, Engine, and Wheels.

    • The CarElementPrintVisitor and CarElementDoVisitor are concrete visitors, each implementing the required visit() operation for every car element.

    Visitor Sample

70. Patterns and You



71. Conclusion