1、单纯策略模式
1)策略基类和子类
class state
{
public:
virtual void process() = 0;
};
class state_init : virtual public state
{
public:
virtual void process(){
cout << "state_init. process" << endl;
}
};
class state_routing : virtual public state
{
public:
virtual void process(){
cout << "state_routing. process" << endl;
}
};
class state_execute : virtual public state
{
public:
virtual void process(){
cout << "state_execute. process" << endl;
}
};
2)环境类
class statecontext
{
public:
statecontext(state* state){
m_state = state;
}
~statecontext(){
if (m_state){
delete m_state;
}
}
public:
void process(){
if (m_state){
m_state->process();
}
}
private:
state* m_state;
};
3)应用
int main()
{
statecontext* pcon_init = new statecontext(new state_init());
statecontext* pcon_route = new statecontext(new state_routing());
statecontext* pcon_execute = new statecontext(new state_execute());
if (pcon_init){
pcon_init->process();
delete pcon_init;
pcon_init = NULL;
}else{
cout << "pcon_init is null" << endl;
}
if (pcon_route){
pcon_route->process();
delete pcon_route;
pcon_route = NULL;
}else{
cout << "pcon_route is null" << endl;
}
if (pcon_execute){
pcon_execute->process();
delete pcon_execute;
pcon_execute = NULL;
}else{
cout << "pcon_execute is null" << endl;
}
return 0;
}
2、策略模式与简单工模式结合(和纯策略不同之处在于环境类,对于外界而言隔离了策略,调用更加简单)
class statecontext
{
public:
statecontext(const string& state){
if (state == "init"){
m_state = new state_init();
}else if (state == "routing"){
m_state = new state_routing();
}else if (state == "execute"){
m_state = new state_execute();
}else{
m_state = NULL;
}
}
~statecontext(){
if (m_state){
delete m_state;
}
}
public:
void process(){
if (m_state){
m_state->process();
}
}
private:
state* m_state;
};
3)应用
int main()
{
statecontext* pcon_init = new statecontext("init");
statecontext* pcon_route = new statecontext("routing");
statecontext* pcon_execute = new statecontext("execute");
if (pcon_init){
pcon_init->process();
delete pcon_init;
pcon_init = NULL;
}else{
cout << "pcon_init is null" << endl;
}
if (pcon_route){
pcon_route->process();
delete pcon_route;
pcon_route = NULL;
}else{
cout << "pcon_route is null" << endl;
}
if (pcon_execute){
pcon_execute->process();
delete pcon_execute;
pcon_execute = NULL;
}else{
cout << "pcon_execute is null" << endl;
}
return 0;
}