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

    #include <iostream>
    #include <string>
    
    using namespace std;
    
    class Stratergy {
    
    public:
        virtual void AlgoInterface() = 0;  //注意,基类的虚函数需要有实现,否则会出现Link2001错误;也可以定义为纯虚函数来解决.
    };
    
    class ConcreteStragergyA : public Stratergy {
    
    public:
        void AlgoInterface();
    
    };
    
    class ConcreteStragergyB : public Stratergy {
    
    public:
        void AlgoInterface();
    
    };
    
    class ConcreteStragergyC : public Stratergy {
    
    public:
        void AlgoInterface();
    
    };
    
    class Context {
    public:
        Context(): m_st(NULL) {}
        Context(string type);
        ~Context();
    
        void getRlt();
    
    private:
        Stratergy *m_st;
    };
    
    void ConcreteStragergyA::AlgoInterface() {
        cout<<"This is A algo"<<endl;
    }
    
    void ConcreteStragergyB::AlgoInterface() {
        cout<<"This is B algo"<<endl;
    }
    
    void ConcreteStragergyC::AlgoInterface() {
        cout<<"This is C algo"<<endl;
    }
    
    Context::Context(string type) {
        if (type == "A") {
            m_st = new ConcreteStragergyA();
        } else if (type == "B") {
            m_st = new ConcreteStragergyB();
        } else {
            m_st = new ConcreteStragergyC();
        }
    }
    
    Context::~Context() {
        if (m_st) {
            delete m_st;
        }
    }
    
    void Context::getRlt() {
        if (m_st) {
            m_st->AlgoInterface();
        }
    }
    
    void main() {
    
        {
            Context A("A");
            A.getRlt();
            Context B("B");
            B.getRlt();
            Context C("C");
            C.getRlt();
        }
    
        system("pause");
    }

    注解:

    1. 更加抽象低耦合,使用中用户只需使用Context类,不必关注每个strategy的实现。

  • 相关阅读:
    Linux——端口命令
    Linux——iptables 禁止 IP和端口
    CE第9关共用
    获得程序窗体标题-FindWindowW需要的参数
    mysql ODBC win10 设置
    Work
    Pet
    Is It A Tree?
    Ice_cream's world I
    小希的迷宫
  • 原文地址:https://www.cnblogs.com/hushpa/p/4424079.html
Copyright © 2011-2022 走看看