Design Patterns 2
Design Patterns 2
(TIC++V2:C10)
Outline
What For How Examples
1. queue a set of actions to be performed collectively 2. object-oriented callbacks (run can be executed at any desired time). 3. Callbacks are essential to even-driven programming. We can use Command to collect all event handlers and execute run when the related event occurs. 4. Undo: Each time the user performs an operation, the corresponding undo Command object is placed into a queue. Each Command object that is executed backs up the state of the program by one step.
Other Names of Command Pattern: function object functor
State Pattern
State Pattern
State Pattern: provides a surrogate class to its implementation classes and allows dynamic change of implementations. Applications: Like Proxy, State is created by having a front-end object that uses a back-end implementation object to fulfill its duties. However, the State pattern switches from one implementation to another during the lifetime of the front-end object, in order to produce different behavior for the same function call(s). Relationship between the surrogate class and the implementation classes: (Note a proxy class has only one implementation class as shown in the bottom figure).
int main() { Creature creature; creature.greet(); creature.kiss(); creature.greet(); creature.return2palace(); creature.greet(); } ///:~
An important characteristic of the Template Method is that it is defined in the base class and cannot be changed the Template Method is the thing that stays the same. It calls other base-class functions (the ones you override) in order to do its job, but the client programmer isnt necessarily able to call it directly. Note that the Template Method is the code that stays the same, and the functions that you override are the code that changes. However, this change is fixed at compile time via inheritance.
Strategy : Example
class NameStrategy {public: virtual void greet() = 0; }; class SayHi : public NameStrategy { public: void greet() {cout << "Hi! How's it going?" << endl; }}; class Ignore : public NameStrategy { public: void greet() { cout << "(Pretend I don't see you)" << endl; }}; class Admission : public NameStrategy { public: void greet() { cout << "I'm sorry. I forgot your name." << endl; }}; class Context { NameStrategy& strategy; public: Context(NameStrategy& strat) : strategy(strat) {} void greet() { strategy.greet(); } }; int main() { SayHi sayhi; Ignore ignore; Admission admission; Context c1(sayhi), c2(ignore), c3(admission); c1.greet(); c2.greet(); c3.greet(); } ///:~