美文网首页
策略模式

策略模式

作者: 张霸天 | 来源:发表于2017-03-02 19:33 被阅读0次

#include <stdio.h>
#include <iostream>
using namespace std;
class CashSuper {
    
public:
    virtual ~CashSuper(){};
    virtual double acceptCash(double money){return 0;};
};

class CashNormal:public CashSuper {
    
public:
    double acceptCash(double money){return  money;};
};

class CashRebate:public CashSuper {
private:
    double moneyRebate = 1.0;
    
public:
    CashRebate(double moneyRebate):moneyRebate(moneyRebate){};
    double acceptCash(double money){return  money * moneyRebate;};
};


class CashReturn:public CashSuper {
private :
    double moneyCondition = 0.0;
    double moneyReturn = 0.0;
    
public:
    CashReturn(double moneyCondition,double moneyReturn) :moneyCondition(moneyCondition),moneyReturn(moneyReturn) {};
    
    double acceptCash(double money){
        double result = money;
        if (money >= moneyCondition) {
            result = money - int (money / moneyCondition) * moneyReturn;
        }
        return result;
    };
};

class CashFactory {
    
public:
    static CashSuper * createCashAccept(int type)
    {
        CashSuper * cs = NULL;
        switch (type) {
            case 0:
                cs = new CashNormal();
                break;
            case 1:
                cs = new CashReturn(300,100);
                break;
            case 2:
                cs = new CashRebate(0.8);
                break;
            default:
                break;
        }
        return cs;
    }
};

class CashContext {
private:
    CashSuper * cs;
    
public:
    CashContext(int type) {
        cs = CashFactory::createCashAccept(type);
    }
    double getResult(double money)
    {
        return cs->acceptCash(money);
    }
};



void testLesson2() {
    CashContext * context = new CashContext(cashreturn);
    double result = context->getResult(500);
    cout<<result<<endl;
}


比较重要的概念

策略模式 ,咱们只讲用法和好处,用法的就是将实现相同方法的类来个集合,不要求是同一个父类 ,只要是实现这个方法就ok,在c++中不是有多重继承吗,不管是汽车会叫还是动物会叫,都有个会叫的属性,你只要把具有会叫方法的给这个context,就ok,和简单工厂的区别就是,工厂产生的是相同的父类对象,在不同语言中实现方式不一样,在c++中大家可能看到的是class(真的不敢说oc的protocal啊,这个就是有点傻傻分不清),在别的单继承语言中就是别的方法,但思想上我们要把他当成是实现某种特定方法的类聚集,我上面的代码是简单工厂和策略模式的集合。

学术说法
策略模式是一种定义一系列算法的方法,从概念上讲,这些算法完成的都是相同的工作,只是实现不同

相关文章

网友评论

      本文标题:策略模式

      本文链接:https://www.haomeiwen.com/subject/gpukgttx.html