策略模式

来源:互联网 发布:overlay network 网络 编辑:程序博客网 时间:2024/06/05 15:55

             策略模式定义了一系列的算法,并将每一个算法封装起来,而且使它们还可以相互替换。策略模式让算法独立于使用它的客户而独立变化。
            策略模式在应用时,是根据不同的使用情况动态的选择使用的算法,对于客户来说,提供了很好的可扩展性和封闭性。
             
                  下面是代码示例:
                  

#ifndef STRATEGY_H
#define STRATEGY_H
#include <iostream>
class Strategy//策略基类
{
public:
    Strategy();
    virtual ~Strategy(){std::cout << "~~\n";}
    virtual void fun() = 0;
};
#endif // STRATEGY_H
#include "strategy.h"
Strategy::Strategy()
{
}
#ifndef STRATEGYA_H
#define STRATEGYA_H
#include "strategy.h"
class StrategyA : public Strategy
{
public:
    StrategyA();
    ~StrategyA(){}
    void fun();
};
#endif // STRATEGYA_H
#include "strategya.h"
StrategyA::StrategyA()
{
}
void StrategyA::fun()
{
    std::cout << "策略A!走为上" <<'\n';
}
#ifndef STRATEGYB_H
#define STRATEGYB_H
#include "strategy.h"
class StrategyB : public Strategy
{
public:
    StrategyB();
    ~StrategyB(){}
    void fun();
};
#endif // STRATEGYB_H
#include "strategyb.h"
StrategyB::StrategyB()
{
}
void StrategyB::fun()
{
    std::cout << "策略B!老婆天下第一,逛街去" <<'\n';
}
#ifndef STRATEGYC_H
#define STRATEGYC_H
#include "strategy.h"
class StrategyC : public Strategy
{
public:
    StrategyC();
    ~StrategyC(){}
    void fun();
};
#endif // STRATEGYC_H
#include "strategyc.h"
StrategyC::StrategyC()
{
}
void StrategyC::fun()
{
    std::cout << "策略C!金蝉脱壳" <<'\n';
}
#ifndef CONTEXT_H
#define CONTEXT_H
#include "strategy.h"
class Context//应用的上下文类
{
public:
    Context();
    Context(Strategy *p);
    ~Context(){delete p_stratery;}
    void setStratery(Strategy *p) {delete p_stratery;p_stratery = p;}
    void useStratery() const {if(p_stratery != 0)p_stratery->fun();}
private:
    Strategy *p_stratery;
};
#endif // CONTEXT_H
#include "context.h"
Context::Context():p_stratery(0)
{
}
Context::Context(Strategy *p):p_stratery(p)
{
}
#include <iostream>
using namespace std;
#include "context.h"
#include "strategya.h"
#include "strategyb.h"
#include "strategyc.h"
int main()
{
    cout << "老班让加班!策略A..." << '\n';
    Context me(new StrategyA);
    me.useStratery();
    cout << "老婆让逛街!策略B..." << '\n';
    me.setStratery(new StrategyB);
    me.useStratery();
    cout << "兄弟叫喝酒!可老婆让早点回家!策略C..." << '\n';
    me.setStratery(new StrategyC);
    me.useStratery();
    return 0;
}
最后来张运行图

原创粉丝点击