Chapter 26 - An Introduction to Design Patterns


Chapter Goals



An Introduction to Design Patterns


26.1 Iterators


26.1 Iterators (cont.)


26.1 Iterators (cont.)


26.1 Iterators (cont.)

Consider the interface:

A stack has:
  • push
  • pop
  • top

26.1 Iterators (cont.)

A array structure w/random access has:
  • operator[]
  • push_back
  • size

26.1 Iterators (cont.)


26.1 Iterators (cont.)

Interface for list w/cursor

T get() const // Get element at cursor
void set(const T& t) // Set element at cursor to t
T remove() // Remove element at cursor
void insert(const T& t) // Insert t before cursor
void reset() // Reset cursor to head
void next() // Advance cursor
bool is_done() // Check if cursor can be advanced

26.1 Iterators (cont.)

Cursors


26.1 Iterators (cont.)

Cursors (cont.)


26.1 Iterators (cont.)

Drawbacks of cursors


26.1 Iterators (cont.)


26.2 The Pattern Concept


26.2 The Pattern Concept


Pattern ITERATOR


Context

  1. An object (aggregate) contains other objects (elements)
  2. Clients need access
  3. Aggregate should not expose its internals
  4. Multiple clients may need simultaneous access

Pattern ITERATOR (cont.)


Solution

  1. Define an iterator class
    • External
    • Fetches one element at a time
  2. Each iterator object needs to keep track of the position of the next element to fetch

Pattern ITERATOR (cont.)


Solution


26.2 The Pattern Concept (cont.)


26.2 The Pattern Concept (cont.)

Input streams as example of iterator pattern:


26.2 The Pattern Concept (cont.)


Advanced Topic 26.1


Generic Programming with Inheritance and Templates


Advanced Topic 26.1 (cont.)



26.3 The ADAPTER Pattern


26.3 The ADAPTER Pattern (cont.)


Pattern ADAPTER


Context

  1. You want to use an existing class (adaptee) w/out modifying it
  2. The context requires conformance to a target i/f, different from the adaptee's
  3. Target i/f and adaptee i/f are conceptually related

Pattern ADAPTER (cont.)


Solution

  1. Define an adapter class that implements the target i/f
  2. Adapter class translates target functions to adaptee functions
  3. The client wraps the adaptee into an adapter class object

Pattern ADAPTER (cont.)


Solution


26.3 The ADAPTER Pattern (cont.)


26.3 The ADAPTER Pattern (cont.)

Other ADAPTERS:


26.3 The ADAPTER Pattern (cont.)


26.3 The ADAPTER Pattern (cont.)


26.4 The TEMPLATE METHOD Pattern


26.4 The TEMPLATE METHOD Pattern (cont.)

Example - stream buffers


26.4 The TEMPLATE METHOD Pattern (cont.)

Example - stream buffers (cont.)


26.4 The TEMPLATE METHOD Pattern (cont.)

Example - stream buffers (cont.)


26.4 The TEMPLATE METHOD Pattern (cont.)

Example - stream buffers (cont.)


26.4 The TEMPLATE METHOD Pattern (cont.)

Example - stream buffers (cont.)


26.4 The TEMPLATE METHOD Pattern (cont.)


Pattern TEMPLATE METHOD


Context

  1. An algorithm is applicable for multiple types
  2. Algorithm can be broken into primitive operations
  3. The order of execution of the primitives doesn't depend on the type

Pattern TEMPLATE METHOD


Solution

  1. Define the algorithm in the base class
  2. The algorithm calls the primitive operations in order
  3. Define the primitive operations as virtual functions in base class, with appropriate default behavior, or leave undefined
  4. Each derived class defines the primitives, but not the algorithm

26.4 The TEMPLATE METHOD Pattern (cont.)


26.5 Function Objects and the STRATEGY Pattern

26.5.1 Function Objects


26.5.1 Function Objects (cont.)


26.5.1 Function Objects (cont.)


26.5.1 Function Objects (cont.)


26.5.1 Function Objects (cont.)


26.5.1 Function Objects (cont.)


26.5.1 Function Objects (cont.)


26.5.2 The STRATEGY Pattern


Pattern STRATEGY


Context

  1. A class (the context class) can benefit from variants on an algorithm
  2. Clients of the context class can supply custom versions of the algorithm

Pattern STRATEGY


Solution

  1. Define the strategy i/f, an abstraction for the algorithm
  2. Concrete strategy classes implement the strategy i/f; each class defines a version of the algorithm
  3. Client supplies a concrete strategy object to the context class
  4. The context class calls the appropriate functions of the strategy object

26.5.2 The STRATEGY Pattern


26.6 The COMPOSITE Pattern


26.6 The COMPOSITE Pattern (cont.)


26.6 The COMPOSITE Pattern (cont.)


Pattern COMPOSITE


Context

  1. Primitive objects can be combined into composite objects
  2. Clients treat a composite as a primitive

Pattern COMPOSITE


Solution

  1. Define a class that is an abstraction for the primitive objects
  2. Both primitive and composite classes inherit from that class
  3. A composite object contains a collection of primitives
  4. An operation on a composite class is applied to its primitives, results are combined

Pattern COMPOSITE


Solution (cont.)


26.6 The COMPOSITE Pattern (cont.)


26.7 Case Study: Putting Patterns to Work


26.7 Case Study: Putting Patterns to Work (cont.)


26.7 Case Study: Putting Patterns to Work (cont.)


26.7 Case Study: Putting Patterns to Work (cont.)


26.7 Case Study: Putting Patterns to Work (cont.)


26.7 Case Study: Putting Patterns to Work (cont.)


26.7 Case Study: Putting Patterns to Work (cont.)


26.7 Case Study: Putting Patterns to Work (cont.)


26.7 Case Study: Putting Patterns to Work (cont.)


26.7 Case Study: Putting Patterns to Work (cont.)


26.7 Case Study: Putting Patterns to Work (cont.)


26.7 Case Study: Putting Patterns to Work (cont.)


26.7 Case Study: Putting Patterns to Work (cont.)


26.7 Case Study: Putting Patterns to Work (cont.)


26.7 Case Study: Putting Patterns to Work (cont.)


26.7 Case Study: Putting Patterns to Work (cont.)


26.7 Case Study: (product.h)


26.7 Case Study: (item.h)


26.7 Case Study: (productitem.h)


26.7 Case Study: (bundle.h)


26.7 Case Study: (itemiterator.h)


26.7 Case Study: (invoiceprinter.h)


26.7 Case Study: (simpleinvoiceprinter.h)


26.7 Case Study: (invoice.h)


26.7 Case Study: (product.cpp)


26.7 Case Study: (item.cpp)


26.7 Case Study: (productitem.cpp)


26.7 Case Study: (bundle.cpp)


26.7 Case Study: (itemiterator.cpp)


26.7 Case Study: (simpleinvoiceprinter.cpp)


26.7 Case Study: (invoice.cpp)


26.7 Case Study: (invoicetest.cpp)


More Patterns

Quick table of patterns from Design Patterns:

Pattern Name Description Example
Abstract Factory An abstract class defines methods that construct related products. Concrete factories create these product sets An abstract class specifies methods for constructing buttons, methods, and so on. Each user interface look and feel supplies a concrete subclass
Bridge An abstraction and its implementation have separate inheritance hierarchies A hierarchy of window types has separate implementations in various operating systems
Builder A builder class has methods to build parts of a complex product, and to retrieve the completed product A document builder has methods to build paragraphs, tables, and so on

More Patterns (cont.)

Pattern Name Description Example
Chain of Responsibility A request is passed to the first handler in a chain. Each handler acts on the request (or chooses not to act), and passes the request on to the next handler An event-handling mechanism passes a mouse or key event to a component, which then passes it to the parent component
Command Commands are implemented as objects A word processor stores recently issued commands so that they can be undone
Decorator The behavior of a class is enhanced, keeping its interface A user interface component is decorated with scroll bars or borders
Facade A complex subsystem is accessed through a single class A driver class provides access to the functionality of a database system

More Patterns (cont.)

Pattern Name Description Example
Factory Method A virtual constructor can be redefined by derived classes Collection classes that derive from a common base class redefine the create_iterator function
Flyweight Uses shared objects instead of large numbers of separate objects with identical state A word processor uses shared objects for styled characters rather than a separate object for each character
Interpreter A class hierarchy represents grammar rules. The interpreter recursively evaluates a parse tree of rule objects A program interactively evaluates mathematical expressions by building and evaluating a parse tree

More Patterns (cont.)

Pattern Name Description Example
Mediator An object encapsulates the interaction of other objects All components in a dialog box notify a mediator of state changes. The mediator updates affected components
Memento An object yields an opaque snapshot of a part of its state, and can later return its state from that snapshot An undo mechanism requests a memento from an object before mutating it. If the operation is undone, the memento is used to roll the object back to its old state
Observer An object wants to be notified when another object generates an event User interface components generate events, such as button clicks and text changes. A dialog box observes the events and repaints its contents

More Patterns (cont.)

Pattern Name Description Example
Proxy A service needs to be made more versatile without affecting the service provider or client A proxy class sends client requests to a server object on a different computer
Singleton All clients need access to a single shared object of a class A random number singleton gives all clients access to the same generator
State A separate object is used for each state. State-dependent code is distributed over the various state classes An image editor has different drawing states. Each state is handled by a separate tool object
Visitor A structure with a fixed set of element classes needs an extensible set of operations An XML visitor visits a tree of XML elements, applying arbitrary operations to each node

Chapter Summary


  1. Iterators are preferred to cursors
  2. A design pattern uses a standard format to give proven advice about a problem in software design
  3. The ITERATOR pattern teaches how to access the elements of an aggregate object
  4. The ADAPTER pattern teaches how to use a class in a context that requires a different interface
  5. The STRATEGY pattern teaches how to supply variants of an algorithm to a client
  6. The TEMPLATE METHOD pattern teaches how to supply varying behavior patterns to an algorithm
  7. The COMPOSITE pattern teaches how to combine several objects into an object that has the same behavior as its parts
  8. Design patterns apply in specific situations that are described by the context and solution parts of the pattern