Академический Документы
Профессиональный Документы
Культура Документы
The following slides describe several case studies using C++ & patterns
to build highly extensible software
The examples include
1. Expression Tree
{ e.g., Adapter, Factory, Bridge
2. System Sort
{ e.g., Facade, Adapter, Iterator, Singleton, Factory Method, Strategy,
Bridge
3. Sort Verier
{ e.g., Strategy, Factory Method, Facade, Iterator, Singleton
Douglas C. Schmidt
Professor
Department of EECS
d.schmidt@vanderbilt.edu
Vanderbilt University
www.dre.vanderbilt.edu/schmidt/ (615) 343-8197
Vanderbilt University
OO Pattern Examples
Douglas C. Schmidt
Douglas C. Schmidt
OO Pattern Examples
_
UNARY
NODE
Douglas C. Schmidt
BINARY
NODES
+
5
44
INTEGER
NODES
Vanderbilt University
Vanderbilt University
OO Pattern Examples
op_
num_
binary_
MEMORY
LAYOUT
Vanderbilt University
1|2
unary_
use_
Tree
Node
Tree
Node
RELATIONSHIPS
CLASS
object
6
Vanderbilt University
Algorithmic Version
Vanderbilt University
OO Pattern Examples
Douglas C. Schmidt
Vanderbilt University
Do
Expression trees
{ Trees may be \evaluated" via dierent traversals
e.g., in-order, post-order, pre-order, level-order
{ The evaluation step may perform various operations, e.g.,
Traverse & print the expression tree
Return the \value" of the expression tree
Generate code
Perform semantic analysis
tag_
OO Pattern Examples
OO Pattern Examples
D
OO Pattern Examples
Douglas C. Schmidt
Vanderbilt University
OO Pattern Examples
OO Alternative
Douglas C. Schmidt
OO Pattern Examples
Vanderbilt University
OO Pattern Examples
Vanderbilt University
10
Douglas C. Schmidt
_
UNARY
NODE
Douglas C. Schmidt
BINARY
NODES
+
5
44
INTEGER
NODES
Vanderbilt University
11
OO Pattern Examples
Douglas C. Schmidt
Unary
Node
Int
Node
OO Pattern Examples
1
Ternary
Node
2
3
Node
1
Tree
Vanderbilt University
OO Pattern Examples
-a
has
12
Douglas C. Schmidt
Vanderbilt University
14
Douglas C. Schmidt
Factory
{ Centralize the assembly of resources necessary to create an object
e.g., decouple Node subclass initialization from use
Bridge
{ Decouple an abstraction from its implementation so that the two can
vary independently
e.g., printing contents of a subtree and managing memory
Adapter
{ Convert the interface of a class into another interface clients expect
e.g., make Tree conform C++ iostreams
Vanderbilt University
OO Pattern Examples
13
Douglas C. Schmidt
#include "Node.h"
// Bridge class that describes the Tree edges and
// acts as a Factory.
class Tree {
public:
// Factory operations
Tree (int);
Tree (const string &, Tree &);
Tree (const string &, Tree &, Tree &);
Tree (const Tree &t);
void operator= (const Tree &t);
~Tree ();
void print (std::ostream &) const;
private:
Node *node_; // pointer to a rooted subtree
Vanderbilt University
15
Vanderbilt University
right_
right
(Tree
(TreePART
PART))
Binary
Node
num_
num
PART
PART
right_
right
(Tree
(TreePART
PART))
PART
PART
PART
PART
operator_
operator
op
op
tag
tag
operator_
operator
operator_
operator
Tree
left_
left
(Tree
(TreePART
PART))
left_
left
(Tree
(TreePART
PART))
operand_
operand
(Tree
(TreePART
PART))
vptr
vptr
middle_
middle
(Tree
PART))
(TreePART
Node
Node
Node
Node
Node
Node
Node
Node
PART
PART
node_
ptr
Unary Node
Node
Ternary
Node
Int_Node
#include "Node.h"
18
Douglas C. Schmidt
OO Pattern Examples
Vanderbilt University
16
17
Douglas C. Schmidt
Vanderbilt University
#include "Node.h"
OO Pattern Examples
Douglas C. Schmidt
#include "Node.h"
OO Pattern Examples
Vanderbilt University
use_
use
Do
OO Pattern Examples
Douglas C. Schmidt
Vanderbilt University
#include "Binary_Node.h"
22
Douglas C. Schmidt
OO Pattern Examples
20
Vanderbilt University
#include "Int_Node.h"
OO Pattern Examples
Douglas C. Schmidt
23
Problem
{ How to ensure the Node subclasses are initialized properly
Forces
{ There are dierent types of Node subclasses
e.g., take dierent number & type of arguments
{ We want to centralize initialization in one place because it is likely to
change . . .
Solution
{ Use a Factory pattern to initialize the Node subclasses
Vanderbilt University
Douglas C. Schmidt
OO Pattern Examples
21
Vanderbilt University
#include "Unary_Node.h"
OO Pattern Examples
OO Pattern Examples
OO Pattern Examples
OO Pattern Examples
24
Douglas C. Schmidt
The Factory pattern is used by the Tree class to initialize Node subclasses:
creates
Product product = ...
return product
Product
Vanderbilt University
OO Pattern Examples
Vanderbilt University
26
Douglas C. Schmidt
make_product()
Intent
{ Centralize the assembly of resources necessary to create an object
Decouple object creation from object use by localizing creation
knowledge
This pattern resolves the following forces:
{ Decouple initialization of the Node subclasses from their subsequent
use
{ Makes it easier to change or add new Node subclasses later on
e.g., Ternary nodes . . .
A generalization of the GoF Factory Method pattern
Vanderbilt University
Douglas C. Schmidt
25
Printing Subtrees
Douglas C. Schmidt
Problem
{ How do we print subtrees without revealing their types?
Forces
{ The Node subclass should be hidden within the Tree instances
{ We don't want to become dependent on the use of Nodes, inheritance,
& dynamic binding, etc.
{ We don't want to expose dynamic memory management details to
application developers
Solution
{ Use the Bridge pattern to shield the use of inheritance & dynamic
binding
Vanderbilt University
27
OO Pattern Examples
Douglas C. Schmidt
OO Pattern Examples
Intent
{ Decouple an abstraction from its implementation so that the two can
vary independently
This pattern resolves the following forces that arise when building
extensible software with C++
1. How to provide a stable, uniform interface that is both closed & open,
i.e.,
{ interface is closed to prevent direct code changes
{ Implementation is open to allow extensibility
2. How to manage dynamic memory more transparently & robustly
3. How to simplify the implementation of operator<<
Vanderbilt University
OO Pattern Examples
28
Douglas C. Schmidt
Node
print()
print()
Implementor
Abstraction
method_impl()
method()
Concrete
ImplementorA
method_impl()
Concrete
ImplementorB
method_impl()
Vanderbilt University
OO Pattern Examples
29
Douglas C. Schmidt
1: print()
Tree
Douglas C. Schmidt
Int Node
Ternary
print() Binary
Node
Node Unary print()
print()
Node
Note how this pattern decouples the Tree interface for printing from the
Node subclass implementation
{ i.e., the Tree interface is xed, whereas the Node implementation
varies
{ However, clients need not be concerned about the variation . . .
print()
Vanderbilt University
30
Vanderbilt University
31
OO Pattern Examples
Douglas C. Schmidt
Problem
{ Our Tree interface uses a print method, but most C++ programmers
expect to use I/O Streams
Forces
{ Want to integrate our existing C++ Tree class into the I/O Stream
paradigm without modifying our class or C++ I/O
Solution
{ Use the Adapter pattern to integrate Tree with I/O Streams
Vanderbilt University
OO Pattern Examples
32
Douglas C. Schmidt
OO Pattern Examples
Intent
{ Convert the interface of a class into another interface client expects
Adapter lets classes work together that couldn't otherwise because
of incompatible interfaces
This pattern resolves the following force:
1. How to transparently integrate the Tree with the C++ istd::ostream
operators
Vanderbilt University
OO Pattern Examples
33
Adapter
request()
Vanderbilt University
Douglas C. Schmidt
1: operator<<
1: request ()
client
Douglas C. Schmidt
Target
client
Target
operator<<
request()
Tree
iostream
Adaptee
operator<<
2: specific_request() specific_request()
34
Vanderbilt University
2: print()
print()
35
Douglas C. Schmidt
Tree::~Tree () {
// Ref-counting, garbage collection
--this->node_->use_;
if (this->node_->use_<= 0)
delete this->node_;
Vanderbilt University
38
Douglas C. Schmidt
OO Pattern Examples
36
Note how the C++ code shown above uses I/O streams to \adapt" the
Tree interface . . .
Vanderbilt University
OO Pattern Examples
Douglas C. Schmidt
Vanderbilt University
return 0;
// Destructors of t1 \& t2 recursively
} // delete entire tree when leaving scope.
39
Douglas C. Schmidt
OO Pattern Examples
#include <istd::ostream.h>
#include "Tree.h"
37
Vanderbilt University
OO Pattern Examples
t1
#include "Node.h"
class Ternary_Node : public Node {
public:
Ternary_Node (const string &, const Tree &,
const Tree &, const Tree &);
virtual void print (std::ostream &) const;
private:
const string operation_;
Tree left_, middle_, right_; };
Douglas C. Schmidt
Vanderbilt University
42
t2
t1
Int
Node
43
Douglas C. Schmidt
#include "Ternary_Node.h"
Ternary_Node::Ternary_Node (const string &op,
const Tree &a,
const Tree &b,
const Tree &c)
: operation_ (op), left_ (a), middle_ (b),
right_ (c) {}
OO Pattern Examples
Do
OO Pattern Examples
Vanderbilt University
Vanderbilt University
Binary
Node
Unary
Node
print(
)
OO Pattern Examples
Vanderbilt University
Int
Node
4
3
5
Unary
Node
Binary
Node
print(
Do
OO Pattern Examples
Douglas C. Schmidt
Vanderbilt University
46
Douglas C. Schmidt
OO Pattern Examples
44
Vanderbilt University
OO Pattern Examples
47
Vanderbilt University
Douglas C. Schmidt
OO Pattern Examples
45
Vanderbilt University
struct Tree_Node {
enum {
NUM, UNARY, BINARY, TERNARY
} tag_; // same as before
union {
// same as before. But, add this:
struct {
Tree_Node *l_, *m_, *r_;
} ternary_;
} c;
#define ternary_ c.ternary_
};
Douglas C. Schmidt
OO Pattern Examples
50
Vanderbilt University
Douglas C. Schmidt
OO Pattern Examples
48
Vanderbilt University
Douglas C. Schmidt
OO Pattern Examples
Douglas C. Schmidt
Vanderbilt University
51
Douglas C. Schmidt
OO Pattern Examples
49
High-level Forces
Vanderbilt University
OO Pattern Examples
OO Pattern Examples
Douglas C. Schmidt
OO Pattern Examples
// Reusable function:
// template <typename ARRAY> void sort (ARRAY &a);
int main (int argc, char *argv[])
{
parse_args (argc, argv);
Input input;
Douglas C. Schmidt
Vanderbilt University
OO Pattern Examples
52
Douglas C. Schmidt
Vanderbilt University
53
OO Pattern Examples
Options
GLOBAL
Sort_AT
Adapter
Sort
STRATEGIC
COMPONENTS
Line_Ptrs
Sort_AT
Adapter
ARRAY
Sort
TYPE
Access
Table
TACTICAL
COMPONENTS
TYPE
Stack
Vanderbilt University
Douglas C. Schmidt
54
Vanderbilt University
Input
TYPE
Array
55
Douglas C. Schmidt
58
// Prototypes
template <typename ARRAY> void sort (ARRAY &a);
void operator>> (std::istream &, Sort_AT_Adapter &);
void operator<< (std::ostream &, const Sort_AT_Adapter &);
Vanderbilt University
Douglas C. Schmidt
OO Pattern Examples
56
Tactical components
{ Stack
Used by non-recursive quick sort
{ Array
Stores/sorts pointers to lines & elds
{ Access Table
Used to store input
{ Input
Eciently reads arbitrary sized input using only 1 dynamic allocation
& 1 copy
Vanderbilt University
OO Pattern Examples
59
Problem
{ The input to the system sort can be arbitrarily large (e.g., up to 1/2
size of main memory)
Forces
{ To improve performance solution must minimize:
1. Data copying & data manipulation
2. Dynamic memory allocation
Solution
{ Create an Input class that reads arbitrary input eciently
Vanderbilt University
Douglas C. Schmidt
OO Pattern Examples
Douglas C. Schmidt
57
Strategic components
{ System Sort
Facade that integrates everything . . .
{ Sort AT Adapter
Integrates Array & Access Table
{ Options
Manages globally visible options
{ Sort
e.g., both quicksort & insertion sort
Vanderbilt University
OO Pattern Examples
OO Pattern Examples
Douglas C. Schmidt
OO Pattern Examples
ACCESS BUFFER
ACCESS ARRAY
60
Douglas C. Schmidt
Vanderbilt University
OO Pattern Examples
char *Input::recursive_read () {
char buffer[BUFSIZ];
// 1. Read input one character at a time, performing
//
search/replace until EOF is reached or buffer
//
is full.
// 1.a If buffer is full, invoke recursive_read()
//
recursively.
// 1.b If EOF is reached, dynamically allocate chunk
//
large enough to hold entire input
// 2. On way out of recursion, copy buffer into chunk
}
Vanderbilt University
Douglas C. Schmidt
class Input {
public:
// Reads from <input> up to <terminator>, replacing <search>
// with <replace>.
Returns dynamically allocated buffer.
char *read (std::istream &input, int terminator = EOF,
int search = '\n', int replace = '\0');
// Number of bytes replaced.
size_t replaced () const;
// Size of buffer.
size_t size () const;
private:
// Recursive helper method.
char *recursive_read ();
// . . .
};
Vanderbilt University
OO Pattern Examples
62
61
Douglas C. Schmidt
Facade
{ Provide a unied interface to a set of interfaces in a subsystem
Facade denes a higher-level interface that makes the subsystem
easier to use
{ e.g., sort() function provides a facade for the complex internal details
of ecient sorting
Adapter
{ Convert the interface of a class into another interface clients expect
Adapter lets classes work together that couldn't otherwise because
of incompatible interfaces
{ e.g., make Access Table conform to interfaces expected by sort &
istd::ostreams
Vanderbilt University
63
Vanderbilt University
66
Douglas C. Schmidt
OO Pattern Examples
Sort Algorithm
64
Factory
{ Centralize assembly of resources needed to create objects
{ e.g., decouple initialization of Line Ptrs used by Access Table from
their subsequent use
Bridge
{ Decouple an abstraction from its implementation so that the two can
vary independently
{ e.g., comparing two lines to determine ordering
Strategy
{ Dene a family of algorithms, encapsulate each one, & make them
interchangeable
{ e.g., allow
exible pivot selection
Vanderbilt University
Douglas C. Schmidt
OO Pattern Examples
Vanderbilt University
1. Non-recursive
Uses an explicit stack to reduce function call overhead
2. Median of 3 pivot selection
Reduces probability of worse-case time complexity
3. Guaranteed (log n) space complexity
Always \pushes" larger partition
4. Insertion sort for small partitions
Insertion sort runs fast on almost sorted data
67
Douglas C. Schmidt
OO Pattern Examples
Quicksort Optimizations
65
Singleton
{ Ensure a class has only one instance, & provide a global point of
access to it
{ e.g., provides a single point of access for the system sort facade & for
program options
Iterator
{ Provide a way to access the elements of an aggregate object
sequentially without exposing its underlying representation
{ e.g., provides a way to print out the sorted lines without exposing
representation or initialization
Vanderbilt University
Douglas C. Schmidt
OO Pattern Examples
OO Pattern Examples
Douglas C. Schmidt
Problem
{ There are various algorithms for selecting a pivot value
e.g., randomization, median of three, etc.
Forces
{ Dierent input may sort more eciently using dierent pivot
selection algorithms
Solution
{ Use the Strategy pattern to select the pivot selection algorithm
Vanderbilt University
Context
Douglas C. Schmidt
Intent
{ Dene a family of algorithms, encapsulate each one, & make them
interchangeable
Strategy lets the algorithm vary independently from clients that use
it
This pattern resolves the following forces
1. How to extend the policies for selecting a pivot value without modifying
the main quicksort algorithm
2. Provide a one size ts all interface without forcing a one size ts all
implementation
Douglas C. Schmidt
Strategy
Vanderbilt University
OO Pattern Examples
69
Douglas C. Schmidt
P
i vot
Strategy
quick_sort
algorithm_interface()
context_interface()
68
OO Pattern Examples
OO Pattern Examples
get_pivot()
Concrete
Strategy A
Concrete
Strategy C
algorithm_interface()
algorithm_interface()
Select
First
Concrete
Strategy B
Random
Median
of
Three
algorithm_interface()
Vanderbilt University
70
Vanderbilt University
71
private:
T stack_[SIZE];
size_t top_;
};
Vanderbilt University
74
Douglas C. Schmidt
OO Pattern Examples
Fixed-size Stack
72
Douglas C. Schmidt
Vanderbilt University
OO Pattern Examples
Douglas C. Schmidt
Vanderbilt University
75
Problem
{ Although the implementation of the sort function is complex, the
interface should be simple to use
Key forces
{ Complex interface are hard to use, error prone, and discourage
extensibility & reuse
{ Conceptually, sorting only makes a few assumptions about the \array"
it sorts
e.g., supports operator[] methods, size, & trait TYPE
{ We don't want to arbitrarily limit types of arrays we can sort
Solution
{ Use the Facade & Adapter patterns to simplify the sort program
Douglas C. Schmidt
OO Pattern Examples
73
Vanderbilt University
OO Pattern Examples
Douglas C. Schmidt
OO Pattern Examples
Intent
{ Provide a unied interface to a set of interfaces in a subsystem
Facade denes a higher-level interface that makes the subsystem
easier to use
This pattern resolves the following forces:
1. Simplies the sort interface
{ e.g., only need to support operator[] & size methods, & element
EXTERNALLY
VISIBLE
OO Pattern Examples
Facade Pattern
Douglas C. Schmidt
Facade
HIDDEN
TYPE
Vanderbilt University
OO Pattern Examples
EXTERNALLY
VISIBLE
76
Douglas C. Schmidt
ARRAY
Vanderbilt University
OO Pattern Examples
Sort
HIDDEN
ARRAY
TYPE
Stack
Quick
Sort
ARRAY
Insert
Sort
Vanderbilt University
78
77
Douglas C. Schmidt
Problem
{ Command-line options must be global to many parts of the sort
program
Key forces
{ Unrestricted use of global variables increases system coupling & can
violate encapsulation
{ Initialization of static objects in C++ can be problematic
Solution
{ Use the Singleton pattern to centralize option processing
Vanderbilt University
79
OO Pattern Examples
Singleton Pattern
Douglas C. Schmidt
Intent
{ Ensure a class has only one instance, & provide a global point of
access to it
This pattern resolves the following forces:
1. Localizes the creation & use of \global" variables to well-dened
objects
2. Preserves encapsulation
3. Ensures initialization is done after program has started & only on rst
use
4. Allow transparent subclassing of Singleton implementation
OO Pattern Examples
Douglas C. Schmidt
Vanderbilt University
80
OO Pattern Examples
Douglas C. Schmidt
Singleton
static instance()
singleton_operation()
get_singleton_data()
static unique_instance_
singleton_data_
Vanderbilt University
OO Pattern Examples
if (unique_instance_ == 0)
unique_instance_ = new Options;
return unique_instance_;
81
Options Class
Douglas C. Schmidt
Options
static instance()
bool enabled()
field_offset()
static unique_instance_
options_
Vanderbilt University
if (unique_instance_ == 0)
unique_instance_ = new Singleton;
return unique_instance_;
82
Vanderbilt University
83
if (options->enabled (Options::NORMAL))
return strcmp (this->bof_, rhs.bof_) < 0;
Vanderbilt University
86
Douglas C. Schmidt
OO Pattern Examples
84
Vanderbilt University
};
Douglas C. Schmidt
protected:
Options (); // Ensure Singleton.
OO Pattern Examples
Douglas C. Schmidt
87
Problem
{ The comparison operator shown above is somewhat complex
Forces
{ It's better to determine the type of comparison operation during the
initialization phase
{ But the interface shouldn't change
Solution
{ Use the Bridge pattern to separate interface from implementation
Vanderbilt University
Douglas C. Schmidt
OO Pattern Examples
Simplifying Comparisons
85
Vanderbilt University
OO Pattern Examples
OO Pattern Examples
Douglas C. Schmidt
Intent
{ Decouple an abstraction from its implementation so that the two can
vary independently
This pattern resolves the following forces that arise when building
extensible software
1. How to provide a stable, uniform interface that is both closed & open,
i.e.,
{ Closed to prevent direct code changes
{ Open to allow extensibility
2. How to simplify the Line_Ptrs::operator< implementation &
reference counting for Access Table buer
OO Pattern Examples
Vanderbilt University
OO Pattern Examples
Line_Ptrs
88
Douglas C. Schmidt
Concrete
ImplementorA
method_impl()
Concrete
ImplementorB
method_impl()
Vanderbilt University
OO Pattern Examples
Options
89
Douglas C. Schmidt
Vanderbilt University
method_impl()
method()
numcmp()
Implementor
Abstraction
strcmp()
Douglas C. Schmidt
1: method_impl()
compare()
operator<
strcasecmp()
90
Vanderbilt University
91
OO Pattern Examples
Douglas C. Schmidt
Problem
{ How does the
Forces
{ There are many dierent choices for compare, depending on which
options are enabled
{ We only want to worry about initialization details in one place
{ Initialization details may change over time
{ We'd like to do as much work up front to reduce overhead later on
Solution
{ Use a Factory pattern to initialize the comparison operator
Vanderbilt University
OO Pattern Examples
92
Douglas C. Schmidt
1: request ()
Vanderbilt University
93
OO Pattern Examples
sort
request()
Adapter
Adaptee
2: specific_request()
ARRAY
"conforms to"
Line_Ptrs
specific_request()
Sort_AT_Adapter
typedef Line_Ptrs TYPE
make_table()
operator[]
size()
Vanderbilt University
Douglas C. Schmidt
ARRAY::
ARRAY::TYPE
TYPE
operator[]
size()
1: ARRAY::TYPE t
= array[i]
request()
Douglas C. Schmidt
Intent
{ Convert the interface of a class into another interface clients expect
Adapter lets classes work together that couldn't otherwise because
of incompatible interfaces
This pattern resolves the following forces:
1. How to transparently integrate the Access Table with the sort
routine
2. How to transparently integrate the Access Table with the C++
istd::ostream operators
ARRAY
Target
client
OO Pattern Examples
94
Vanderbilt University
TYPE
Access_Table
make_table()
length()
element()
95
Dynamic Array
Vanderbilt University
private:
char *buffer_; // Underlying buffer
size_t ref_count_; // Refcount tracks deletion.
};
void
void
char
void
98
Douglas C. Schmidt
OO Pattern Examples
96
Table
Douglas C. Schmidt
Vanderbilt University
OO Pattern Examples
Douglas C. Schmidt
Vanderbilt University
};
99
struct Line_Ptrs {
// Comparison operator used by sort().
int operator< (const Line_Ptrs &) const;
Douglas C. Schmidt
OO Pattern Examples
97
Vanderbilt University
OO Pattern Examples
OO Pattern Examples
Douglas C. Schmidt
OO Pattern Examples
Vanderbilt University
OO Pattern Examples
100
Douglas C. Schmidt
Douglas C. Schmidt
Intent
{ Centralize the assembly of resources necessary to create an object
Decouple object creation from object use by localizing creation
knowledge
This pattern resolves the following forces:
{ Decouple initialization of the compare operator from its subsequent
use
{ Makes it easier to change comparison policies later on
e.g., adding new command-line options
Vanderbilt University
101
OO Pattern Examples
Douglas C. Schmidt
Options
Factory
parse_args()
make_product()
creates
creates
initialize compare
Compare
Function
Product
Vanderbilt University
102
Vanderbilt University
103
Douglas C. Schmidt
106
Problem
{ One of the nastiest parts of the whole system sort program is initializing
the Access Table
Key forces
{ We don't want initialization details to aect subsequent processing
{ Makes it easier to change initialization policies later on
e.g., using the Access Table in non-sort applications
Solution
{ Use the Factory Method pattern to initialize the Access Table
Vanderbilt University
Douglas C. Schmidt
OO Pattern Examples
104
Vanderbilt University
OO Pattern Examples
107
Intent
{ Dene an interface for creating an object, but let subclasses decide
which class to instantiate
Factory Method lets a class defer instantiation to subclasses
This pattern resolves the following forces:
{ Decouple initialization of the Access Table from its subsequent use
{ Improves subsequent performance by pre-caching beginning of each
eld & line
{ Makes it easier to change initialization policies later on
e.g., adding new command-line options
Vanderbilt University
Douglas C. Schmidt
OO Pattern Examples
105
Vanderbilt University
Douglas C. Schmidt
OO Pattern Examples
OO Pattern Examples
Douglas C. Schmidt
OO Pattern Examples
Douglas C. Schmidt
Creator
TYPE
factory_method() = 0
make_product()
Access Table
make_table() = 0
Product
Concrete
Creator
Sort AT
Adapter
factory_method()
Concrete
Product
make_table()
CREATES
Vanderbilt University
108
OO Pattern Examples
Douglas C. Schmidt
Line Ptrs
Vanderbilt University
OO Pattern Examples
Douglas C. Schmidt
Sort AT Adapter
109
The Access Table Factory class has a Factory Method that initializes
Sort AT Adapter
// Factory Method initializes Access_Table.
int Sort_AT_Adapter::make_table (size_t num_lines,
char *buffer)
{
// Array assignment op.
this->access_array_.resize (num_lines);
this->buffer_ = buffer; // Obtain ownership.
size_t count = 0;
Vanderbilt University
110
Vanderbilt University
111
Vanderbilt University
114
Intent
{ Provide a way to access the elements of an aggregate object
sequentially without exposing its underlying representation
The C++ Standard Library (STL) is heavily based on the iterator pattern,
e.g.,
Douglas C. Schmidt
OO Pattern Examples
112
Iterator Pattern
Vanderbilt University
Douglas C. Schmidt
OO Pattern Examples
return lp;
115
Line_Ptrs Line_Ptrs_Iter::current_element () {
Line_Ptrs lp;
The Iterator pattern provides a way to initialize the Access Table without
knowing how the buer is represented
Vanderbilt University
Douglas C. Schmidt
OO Pattern Examples
113
Problem
{ We'd like to initialize the Access Table without having to know the
input buer is represented
Key force
{ Representation details can often be decoupled from accessing each
item in a container or collection
Solution
{ Use the Iterator pattern to scan through the buer
Vanderbilt University
Douglas C. Schmidt
OO Pattern Examples
Douglas C. Schmidt
118
Vanderbilt University
Douglas C. Schmidt
OO Pattern Examples
116
Vanderbilt University
OO Pattern Examples
Vanderbilt University
Input original;
Input potentially_sorted;
119
Douglas C. Schmidt
OO Pattern Examples
117
Vanderbilt University
Douglas C. Schmidt
OO Pattern Examples
122
Vanderbilt University
Douglas C. Schmidt
OO Pattern Examples
Forces
120
Vanderbilt University
Douglas C. Schmidt
OO Pattern Examples
unsorted
13
4
13
18
15
15
13
18
13
13
13
15
Vanderbilt University
123
Forces (cont'd)
Douglas C. Schmidt
OO Pattern Examples
18
Douglas C. Schmidt
121
sorted, but
not permuted
permuted, but
not sorted
sorted and
permuted
Common Problems
Vanderbilt University
OO Pattern Examples
Douglas C. Schmidt
Vanderbilt University
126
Douglas C. Schmidt
OO Pattern Examples
124
Strategies
Vanderbilt University
OO Pattern Examples
Douglas C. Schmidt
Vanderbilt University
127
Douglas C. Schmidt
OO Pattern Examples
High-level Algorithm
125
Vanderbilt University
OO Pattern Examples
OO Pattern Examples
Douglas C. Schmidt
OO Pattern Examples
Douglas C. Schmidt
TYPE
Search
Struct
LONG
TYPE
Hash
Table
Range
Vector
TYPE
Binary
Search
Nodups
Vanderbilt University
OO Pattern Examples
128
Douglas C. Schmidt
Vanderbilt University
OO Pattern Examples
TYPE
Binary
Search
Dups
129
Douglas C. Schmidt
Vanderbilt University
130
Vanderbilt University
131
Strategy subclasses
OO Pattern Examples
Douglas C. Schmidt
OO Pattern Examples
133
Douglas C. Schmidt
Vanderbilt University
TYPE
};
132
TYPE
Vanderbilt University
Douglas C. Schmidt
TYPE
OO Pattern Examples
Vanderbilt University
Binary
Search
Nodups
Binary
Search
Dups
long
Hash
Table
TYPE
Range
Vector
Search
Struct
Strategy
check_sort
Factory Method
{ Dene an interface for creating an object, but let subclasses decide
which class to instantiate
Factory Method lets a class defer instantiation to subclasses
In addition, the Facade, Iterator, Singleton, & Strategy patterns are used
134
Vanderbilt University
Do
OO Pattern Examples
OO Pattern Examples
Douglas C. Schmidt
OO Pattern Examples
Douglas C. Schmidt
Intent
{ Dene an interface for creating an object, but let subclasses decide
which class to instantiate
Factory Method lets a class defer instantiation to subclasses
This pattern resolves the following force:
1. How to extend the initialization strategy in the sort verier
transparently
Creator
factory_method() = 0
make_product()
Product
Concrete
Creator
factory_method()
Concrete
Product
Vanderbilt University
136
OO Pattern Examples
Douglas C. Schmidt
OO Pattern Examples
New Search
Strategy
New Search
Struct
137
Douglas C. Schmidt
make_strategy()
Search
Struct
Vanderbilt University
Search
Strategy
CREATES
make_strategy()
CREATES
Vanderbilt University
138
Vanderbilt University
139
Vanderbilt University
142
Douglas C. Schmidt
OO Pattern Examples
140
return 0;
// auto_ptr's destructor deletes the memory . . .
Vanderbilt University
Douglas C. Schmidt
OO Pattern Examples
Factory Method
Douglas C. Schmidt
Vanderbilt University
143
Douglas C. Schmidt
OO Pattern Examples
141
Vanderbilt University
OO Pattern Examples
Vanderbilt University
144
Douglas C. Schmidt
OO Pattern Examples
145
Vanderbilt University
Douglas C. Schmidt
OO Pattern Examples