Strategy策略模式是在模板方法模式上的一个改进,模板方法模式是代码复用,这里用组合来解决将变化的代码从“坚持相同的代码”中分开,从而产生Strategy策略模式。 示例代码:
#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?"<<end;}
};
class Ignore:public NameStrategy{
public:
void greet(){cout << "(Pretent 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& strateagy;
pubic:
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();
}
在main()中就可以看到,运行时的策略选择。
Chain of Responsibility职责链模式可看作是一个策略对象的递归调用,本质是尝试多个解决方法,直到找到一个起作用的。实际上它是个链表,可动态创建。这里我们可以用STL来实现。
示例代码:
#include <iostream>
#include <vector>
using namespace std;
enum Answer(NO.YES);
class GimmeStrategy{
public:
virtual Answer canIHave()=0;
virtual ~GimmeStrategy();
};
class AsdRom:public GimmeStrategy{
public:
Answer canIHave(){
cout << "Moom?Can I have this?"<<endl;
return NO;}
};
class AsdDad:public GimmeStrategy{
public:
Answer canIHave(){
cout << "Dad,I really need this!" <<endl;
return NO;}
};
class AsdGrandpa:public GimmeStrategy{
public:
Answet canIHave(){
cout<<"Grandpa.is it my birthday yet?"<<endl;
return YES;}
};
class Gimme:public GimmeStrategy{
vector<GimmeStrategy*> chain;
public:
Gimme(){
chain.push_back(new AskMom());
chain.push_back(new AskDad());
chain.push_back(new AskGrandpa());
chain.push_back(new AskGrandma());
}
Answer canIHave(){
vector<GimmeStrategy*>::iterator it = chain.begin();
while(it != chain.end())
if(*it++)->canIHave()==YES)
return YES;
cout << "Whiiiiinne!"<<endl;
retunr NO;
}
~Gimme(){purge(chain);}
};
int main()
{
Gimme chain;
chain.canIHave();
}
在GOF的原著中,侧重于链表的创建,由于STL的存在,创建链表变得很轻松。