c++策略模式(Strategy Method)

 

别人的博客再讲策略模式时都会讲三国,策略类就是赵云的锦囊,锦囊里装着若干妙计。在打仗时想要用什么妙计,直接从锦囊里去取。

锦囊类:

class context
{
public:
	context(IStrategy *isstrategy);
	~context();
	void Operate(void);
private:
	IStrategy *m_strategy;
	
};
context::context(IStrategy *isstrategy):m_strategy(isstrategy)
{
}
context::~context()
{
}
void context::Operate(void)
{
    m_strategy->Operate();
}

妙计的接口:

class IStrategy
{
public:
	IStrategy(void){};
	virtual ~IStrategy(void){};
	virtual void Operate(void) = 0;
};

走后门妙计:

class BackDoor:public IStrategy
{
public:
    BackDoor(void);
    ~BackDoor(void);
    void Operate(void);
};
BackDoor::BackDoor(void)
{
}
BackDoor::~BackDoor(void)
{
}
void BackDoor::Operate(void)
{
    std::cout <<"走后门了!" <<std::endl;
}

开绿灯妙计:

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

}
GreenLight::~GreenLight(void)
{

}
void GreenLight::Operate(void)
{
    std::cout << "开绿灯了!" << std::endl;
}

主函数:

int main()
{
    std::cout << "#1策略"<<std::endl;
    context*context1 =  new context(new BackDoor());
    context1->Operate();

    std::cout << "#2策略"<<std::endl;
    context*context2 =  new context(new GreenLight());
    context2->Operate();

    getchar(); 
    return 0;
}

运行结果:

#1策略
走后门了!
#2策略
开绿灯了!

 

---恢复内容结束---

posted @ 2013-11-17 16:53  onlycxue  阅读(1202)  评论(0编辑  收藏  举报