• 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策略
    开绿灯了!

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

  • 相关阅读:
    sharepoint email
    After delete Trigger throw error:The row value(s) updated or deleted either do not make the row unique or they alter multiple rows (2 rows).
    ios 开发书籍
    NES 指令
    nes相关开发资料
    nes相关开发资料
    怎样写模拟器
    Zope简介
    C#中new和override区别
    NES 指令
  • 原文地址:https://www.cnblogs.com/onlycxue/p/3428001.html
Copyright © 2020-2023  润新知