策略模式 + 简单工厂模式
2012-06-26 02:19
260 查看
《大话设计模式》实现代码
//cash.h #ifndef _CASH_H_ #define _CASH_H_ #include <string> using namespace std; class CashSuper { public: CashSuper() {} virtual ~CashSuper() {} virtual double acceptCash(double money) {} }; class CashNormal: public CashSuper { public: double acceptCash(double money); }; class CashReturn: public CashSuper { public: CashReturn(double condition = 0.0, double re = 0.0):moneyCondition(condition), moneyReturn(re) {} ~CashReturn() {} double acceptCash(double money); private: double moneyCondition; double moneyReturn; }; class CashRebate: public CashSuper { public: CashRebate(double rate = 1.0): cashRate(rate) {} ~CashRebate() {} double acceptCash(double money); private: double cashRate; }; class CashContext { public: CashContext(const string &type); ~CashContext(); double getResult(double money); void setType(const string &type); private: void setCash(const string &type); CashSuper *cs; }; CashContext::CashContext(const string &type):cs(NULL) { this->setCash(type); } CashContext::~CashContext() { if(cs != NULL) { delete cs; cs = NULL; } } void CashContext::setType(const string &type) { this->setCash(type); } void CashContext::setCash(const string &type) { if(type.compare("Normal") == 0) cs = new CashNormal(); else if(type.compare("Return") == 0) cs = new CashReturn(300.0, 100.0); else if(type.compare("Rebate") == 0) cs = new CashRebate(0.8); else cs = NULL; } double CashContext::getResult(double money) { if(cs != NULL) return cs->acceptCash(money); return 0; } double CashNormal::acceptCash(double money) { return money; } double CashReturn::acceptCash(double money) { double result = money; if(result >= this->moneyCondition && this->moneyCondition > 0) result -= (double)((int) (result / this->moneyCondition)) * this->moneyReturn; return result; } double CashRebate::acceptCash(double money) { return money * cashRate; } #endif
#include <iostream> #include <cstdio> #include <string> #include "cash.h" using namespace std; int main() { string type1("Normal"); string type2("Return"); string type3("Rebate"); double price = 80; int num = 10; CashContext context(type1); printf("The total money is: %.2lf\n", price * num); printf("Noraml strategy: %.2lf\n", context.getResult(price * num)); context.setType(type2); printf("Return strategy: %.2lf\n", context.getResult(price * num)); context.setType(type3); printf("Rebate strategy: %.2lf\n", context.getResult(price * num)); return 0; }
相关文章推荐
- 大话设计模式之策略模式(结合简单工厂),程序完善过程蕴含智慧
- 策略模式与简单工厂模式
- 简单工厂、工厂方法、抽象工厂、策略模式、策略与工厂的区别
- 设计模式笔记——策略模式VS简单工厂模式
- 简单工厂模式和策略模式的区别
- 大话设计模式中简单工厂模式和策略模式的商场收银软件实例的C++代码
- 设计模式1(简单工厂模式,策略模式)
- 策略模式与状态工厂,简单工厂的恩怨
- 简单工厂模式和策略模式的区别(原)
- 简单工厂模式和策略模式理解
- 大话设计模式-----简单工厂模式与策略模式
- 简单工厂+策略模式-上
- 简单工厂、工厂方法、抽象工厂、策略模式、策略与工厂的区别
- 简单工厂模式与策略模式的区别
- 【设计模式】策略模式PK简单工厂模式
- 对设计模式的总结之简单工厂与策略模式
- 简单工厂模式与策略模式
- 简单工厂模式和策略模式
- 简单工厂模式和策略模式结合使用php
- 大话设计模式-策略模式与简单工厂模式