你的位置:首页 > 软件开发 > ASP.net > 设计模式学习历程(二)————从简单工厂到策略模式

设计模式学习历程(二)————从简单工厂到策略模式

发布时间:2016-07-29 17:00:04
学习完了简单工厂模式以后,感觉可以用于解决大多数多算法选择的问题了,接下来看一个新的例子,也是借用《大话数据结构》一书的例子,要实现的是一个商场促销的计算软件,输入商品的单价和数量,还有销售策略(如打折,返现),然后计算出总的价格。  首先可以从这个问题中抽象出两个算法类,一个是 ...

  学习完了简单工厂模式以后,感觉可以用于解决大多数多算法选择的问题了,接下来看一个新的例子,也是借用《大话数据结构》一书的例子,要实现的是一个商场促销的计算软件,输入商品的单价和数量,还有销售策略(如打折,返现),然后计算出总的价格。

  首先可以从这个问题中抽象出两个算法类,一个是打折算法类,需要提供打折的幅度,如八折,另一个是返现算法类,需要提供返现的最小额度和返现金额,如满300减100,它们都有一个共同的方法,计算出总的价格,这里因为每个类里面只有一个计算总价的方法需要用到金额,所以可以直接把总金额作为函数的参数传入,而不用作为算法类的成员变量,用简单工厂模式实现如下:

 1 class Collection 2 { 3 public: 4   virtual float GetSum(float money) { return money; } 5   virtual ~Collection() {} 6 }; 7 class CollectionDiscount :public Collection 8 { 9 private:10   float discount = 1.0f;11 public:12   CollectionDiscount() = default;13   CollectionDiscount(float d):discount(d){}14   float GetSum(float money) override15   {16     return money*discount;17   }18 };19 class CollectionReturn :public Collection20 {21 private:22   float limit=0.0f;23   float value = 0.0f;24 public:25   CollectionReturn() = default;26   CollectionReturn(float l,float v) :limit(l),value(v) {}27   float GetSum(float money) override28   {29     if (money >= limit)30       return money - value;31     else32       return money;33   }34 };35 class CollectionFactory36 {37 public:38   static shared_ptr<Collection> CreateCollection(get='_blank'>string type)39   {40     shared_ptr<Collection> ptr = nullptr;41     if (type == "打八折")42       ptr = make_shared<CollectionDiscount>(0.8);43     else if (type == "满300送100")44       ptr= make_shared<CollectionReturn>(300, 100);45     else46       throw(invalid_argument("没有这种折扣策略"));47     return ptr;48   }49 };
1 int main()2 {3   shared_ptr<Collection> c = CollectionFactory::CreateCollection("打八折");4   cout << c->GetSum(100) << endl;5   return 0;6 }

 

海外公司注册、海外银行开户、跨境平台代入驻、VAT、EPR等知识和在线办理:https://www.xlkjsw.com

原标题:设计模式学习历程(二)————从简单工厂到策略模式

关键词:设计模式

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。