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的实现。

  • 相关阅读:
    2014.7建兰NOIP模拟Day1 Running
    简单的数论函数模板
    二分图匹配的匈牙利算法
    手算平方根
    ...
    hdu 5396 Expression(区间DP+组合数)
    hdu 5693 D Game(区间DP)
    hdu 5151 Sit sit sit(区间dp+排列组合)
    hdu 4570 Multi-bit Trie(dp)
    hdu 2855 Fibonacci Check-up (矩阵)
  • 原文地址:https://www.cnblogs.com/hushpa/p/4424079.html
Copyright © 2011-2022 走看看