zoukankan      html  css  js  c++  java
  • c++设计模式之策略模式

     概念:通过定义一系列封装的算法,使得调度者可以互相替换,此模式让算法的变化,不会影响到使用算法的客户。

    特点:

    1)根据不同的情况创建不同的对象。

    2)每个对象的方法名相同,但实现却不同。

    结构:

    1)一个抽象策略

    2)多个继承策略

    c) 持有一个具体策略类的引用,供客户端使用

    #include<iostream>
    using namespace std;
    /*************************************策略基类****************************************/
    
    class IStrategy//主要定义了虚函数
    {
    public:
        virtual void DoOperation()=0;//说明是纯虚函数(没有实现的虚函数),必须如此声明
    };
    
    /*************************************具体策略类****************************************/
    
    class StrategyA:public IStrategy//策略子类,主要对父类定义的虚方法进行具体实现
    {
    public:
        void DoOperation()
        {
            cout<<"OperationA"<<endl;
        }
    };
    
    class StrategyB:public IStrategy//策略子类,主要对父类定义的虚方法进行具体实现
    {
    public:
        void DoOperation()
        {
            cout<<"OperationB"<<endl;
        }
    };
    
    class StrategyC:public IStrategy//策略子类,主要对父类定义的虚方法进行具体实现
    {
    public:
        void DoOperation()
        {
            cout<<"OperationC"<<endl;
        }
    };
    
    /*************************************调度类****************************************/
    
    class Context //调度类,根据传进来的参数,选择具体某个策略----待优化<参考教程>
    {
    private:
        IStrategy *strategy;
    
    public:
        Context(IStrategy *child)
        {
            strategy=child;
        }
        void DoOperation()
        {
            strategy->DoOperation();
        }
    
    };
    
    /*************************************客户端****************************************/
    int main()
    {
        cout<<"测试程序"<<endl;
    
        //“具体策略类”只在定义多个“调度类”时使用
        Context *Context_A = new Context(new StrategyA());
        Context *Context_B = new Context(new StrategyB()),
        Context *Context_C = new Context(new StrategyC()),
    }
  • 相关阅读:
    Oracle如何查询不等于某数值
    《Linux系列》- 查看Linux日志
    《数据库优化》- MySQL视图
    《数据库优化》- MySQL优化
    《面试经典系列》- MySQL数据库存储引擎
    《面试经典系列》- Java获取反射机制的三种方法
    《面试经典系列》- 从底层理解==和equals的区别
    《面试经典系列》- 乐观锁和悲观锁及其应用场景
    数据结构之HashMap
    收藏学习地址
  • 原文地址:https://www.cnblogs.com/forbeat/p/5075444.html
Copyright © 2011-2022 走看看