• 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()),
    }
  • 相关阅读:
    最近看代码查到的一些函数,稍作整理(2022.4.1)
    Pytorch的repeat函数
    随机数使用小技巧
    Pytorch的Normal
    OMP: Error #15: Initializing libiomp5md.dll, but found libiomp5md.dll already initialized.报错解决办法
    pytorch tensor索引中的none含义
    scheduled sampling 待完善
    Pytorch的nn.Sequential(*modules)中*的理解
    EOFError: Ran out of input报错解决
    conda安装包报错RemoveError:requests is a dependency of conda and cannot be removed from conda
  • 原文地址:https://www.cnblogs.com/forbeat/p/5075444.html
Copyright © 2020-2023  润新知