Design Patterns Were Mentioned Several Times So Far
Design Patterns Were Mentioned Several Times So Far
• Shared across
multiple points in the
code
• Need to share buffer
– Copying is wasteful
– Need to refer to
same object instance
• What about deleting
these instances?
CSE 332: Design Patterns (Part I)
A More Complete Pattern Form: “Command”
• Problem
– Want to issue requests to objects
– Don’t know in advance which request(s) will be made
– Don’t know in advance to what object(s) they will go
• Solution core
– Encapsulate function call parameters and target object
reference inside an “execute” method
• Consequences
– Decouples invocation/execution
– Commands are first-class objects (elevates functions)
– Easy to compose, add new ones
• Example we’ve seen already
– STL function objects
CSE 332: Design Patterns (Part I)
Structure Diagram Example: “Command”
• Shows fixed class/interface roles in the pattern
• Shows fixed relationships between roles
<<Client>> client role command role
<<Invoker>> * <<Command>>
execute ( )
inheritance
<<ConcreteCommand>>
<<Receiver>> execute ( )
action(args) state_
StoreCommand(aCommand)
time
/ / / / / / / /
action() execute()
first()
next()
<<Container>> is_done()
create_iterator() current_item()
<<ConcreteAggregate>>
creates <<ConcreteIterator>>
has-a
CSE 332: Design Patterns (Part I)
Object-Oriented Iterator Example
class StringIterator {
public:
• Object-oriented version of
iterator is natural to implement
StringIterator (char * s) as a class in C++
: s_ (s), current_ (s) {}
• Constructor stores passed
void first () { pointer to C-style string s,
current_ = s_;
} positions current_ at s
• first (re)positions iterator at
void next () {
++current_; the start of the string
} • next moves iterator to the next
bool is_done () { position
return *current_ == 0; • is_done tests whether iterator
}
is at the end of the string
char * current_item () {
return current_;
• current_item returns a pointer
} to the character at the current
iterator position
private:
char *s_;
char *current_;
};
CSE 332: Design Patterns (Part I)
Using an Object-Oriented Iterator
unsigned int letter_count • Iterators naturally support
(StringIterator& si, char c) use in looping constructs
{
unsigned int count = 0;
• Here we show a for loop
for (si.first (); – first is used to initialize
! si.is_done ( ); – is_done used for loop test
si.next ()) – next used to increment
if (*si.current_item () == c) – current_item is used in
++count; loop body’s value comparison
return count; • When the loop completes,
}
the function shown has
– Iterated through entire string
– Counted occurrences of the
character value in the string
– Returned the occurrence
count
Interface Impl
method () = 0; impl_method ();
public private
Adapter
method ();
Interface
method () = 0;
Adapter Impl
method (); impl_method ();