设计模式学习一:strategyPattern

时间:2022-02-26 17:11:24

#ifndef STRATEGYPATTERN_H_
#define STRATEGYPATTERN_H_
#include<iostream>
using namespace std;

//策略接口
class IStrategy
{
public:
IStrategy(void){};
virtual ~IStrategy(void){};
virtual void Operate(void)=0;
};

//策略一

class CBackDoor:public IStrategy
{
public:
CBackDoor(void);
~CBackDoor(void);
void Operate(void);
};

策略二:

class GivenGreenLight:public IStrategy
{
public:
GivenGreenLight(void);
~GivenGreenLight(void);
void Operate(void);
};

//策略三
class BlockEnemy:public IStrategy
{
public:
BlockEnemy(void);
~BlockEnemy(void);
void Operate(void);
};

//锦囊

class CContext
{
public:
CContext(IStrategy* pStrategy);
~CContext(void);
void Operate(void);
private:
IStrategy* m_pStrategy;
};

#endif

#include "strategyPattern.h"
CBackDoor::CBackDoor(void)
{
}
CBackDoor::~CBackDoor(void)
{
}
void CBackDoor::Operate(void)
{
cout<<"找乔国帮忙,让吴国太给孙权施加压力"<<endl;
}

GivenGreenLight::GivenGreenLight(void)
{
}
GivenGreenLight::~GivenGreenLight(void)
{
}
void GivenGreenLight::Operate(void)
{
cout<<"求吴国太开个绿灯,放行!"<<endl;
}

BlockEnemy::BlockEnemy(void)
{
}
BlockEnemy::~BlockEnemy(void)
{
}
void BlockEnemy::Operate(void)
{
cout<<"孙夫人断后,挡住追兵!"<<endl;
}
CContext::CContext(IStrategy* pStrategy)
{
this->m_pStrategy=pStrategy;
}
CContext::~CContext(void)
{
delete this->m_pStrategy;
}
void CContext::Operate(void)
{
this->m_pStrategy->Operate();
}

#include "strategyPattern.h"

int main()
{
CContext* pContext;
cout<< "----------刚刚到吴国的时候拆第一个----------" <<endl;
pContext=new CContext(new CBackDoor);
pContext->Operate();
delete pContext;

cout<< "----------刘备乐不思蜀了,拆第二个了----------" <<endl;
pContext = new CContext(new GivenGreenLight());
pContext->Operate();
delete pContext;
cout<< "----------孙权的小兵追了,咋办?拆第三个----------" <<endl;
pContext = new CContext(new BlockEnemy());
pContext->Operate();
delete pContext;

return 0;

}