Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Programming
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Databases
Mail Systems
openSolaris
Eclipse Documentation
Techotopia.com
Virtuatopia.com
Answertopia.com

How To Guides
Virtualization
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Windows
Problem Solutions
Privacy Policy

  




 

 

Thinking in C++ Vol 2 - Practical Programming
Prev Home Next

Strategy: choosing the algorithm at runtime

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. Following the maxim of prefer composition to inheritance, we can use composition to approach the problem of separating code that changes from code that stays the same, and produce the Strategy pattern. This approach has a distinct benefit: at runtime, you can plug in the code that changes. Strategy also adds a Context which can be a surrogate class that controls the selection and use of the particular strategy object just like State!

Strategy means just that: you can solve a problem in a number of ways. Consider the situation where you ve forgotten someone s name. Here are the different ways you can cope:

//: C10:Strategy.cpp
// The Strategy design pattern.
#include <iostream>
using namespace std;
 
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;
}
};
 
// The "Context" controls the strategy:
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();
} ///:~
 

Context::greet( ) would normally be more complex; it s the analog of the Template Method because it contains the code that doesn t change. But you can see in main( ) that the choice of strategy can be made at runtime. If you go one step further you can combine this with the State pattern and change the Strategy during the lifetime of the Context object.

Thinking in C++ Vol 2 - Practical Programming
Prev Home Next

 
 
   Reproduced courtesy of Bruce Eckel, MindView, Inc. Design by Interspire