模板方法模式是 坚持相同的代码
而被覆盖的函数是 变化的代码
然而,变化在编译时通过继承被固定下来
策略的意思是 可以使用多种方法来解决某个问题
即条条大路通罗马
现在考虑忘记了某个人的姓名
程序可以用不同方法来解决问题
//: C10:Strategy.cpp
// From "Thinking in C++, Volume 2", by Bruce Eckel & Chuck Allison.
// (c) 1995-2004 MindView, Inc. All Rights Reserved.
// See source code use permissions stated in the file 'License.txt',
// distributed with the code package available at www.MindView.net.
// 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();
getchar();
} ///:~
输出
Hi! How's it going?
(Pretend I don't see you)
I'm sorry. I forgot your name.
Context::greet()可以正规地写得更复杂些
类似模板方法模式
因为其中包含不能改变的代码
1906



被折叠的 条评论
为什么被折叠?



