1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
| * Strategy.cpp * 策略模式 * Created on: 2016年3月14日 下午4:30:31 * Author: Wayne 13186259527@163.com */
#include <iostream> #include <math.h> #include <stdlib.h> #include <stdio.h> using namespace std;
class CashSuper { public: virtual double acceptCash(double money) { return 0; } };
class CashNormal: public CashSuper { public: virtual double acceptCash(double money) { return money; } };
class CashRebate: public CashSuper { private: double moneyRebate; public: CashRebate(double mR) { moneyRebate = mR; } virtual double acceptCash(double money) { return money * moneyRebate; } };
class CashReturn: public CashSuper { private: double moneyCondition; double moneyReturn; public: CashReturn(double mC, double mR) { moneyCondition = mC; moneyReturn = mR; } virtual double acceptCash(double money) { double reult = money; if (money >= moneyCondition) { reult = money - floor((money / moneyCondition)) * moneyReturn; } return reult; } };
class Context { private: CashSuper *cs; public: Context(CashSuper * CS) { cs = CS; } double GetResult(double money) { return cs->acceptCash(money); } };
int main(void) { Context *c = NULL; int choice; double money; double result; cout << "请输入金额(>0):\n"; cin >> money; cout << "请输入打折方式:" << endl; cout << "1------原价" << endl; cout << "2------打八折" << endl; cout << "3------满300返100" << endl; while (true) { cin >> choice; if (choice == 1 || choice == 2 || choice == 3) { break; } cout << "输入有误,请输入1、2和3中任一数字" << endl; } switch (choice) { case 1: c = new Context(new CashNormal()); break; case 2: c = new Context(new CashRebate(0.8)); break; case 3: c = new Context(new CashReturn(300, 100)); break; } result = c->GetResult(money); cout << "result = " << result << endl; return 0; }
|