#include <iostream> using namespace std; // 抽象策略基类 class Strategy { public: virtual void Algorithm(const double lhs, const double rhs) = 0; }; class StrategyAdd : public Strategy { public: void Algorithm(const double lhs, const double rhs) { cout << lhs + rhs << endl; } }; class StrategySub : public Strategy { public: void Algorithm(const double lhs, const double rhs) { cout << lhs - rhs << endl; } }; class StrategyMul : public Strategy { public: void Algorithm(const double lhs, const double rhs) { cout << lhs * rhs << endl; } }; class StrategyDiv : public Strategy { public: void Algorithm(const double lhs, const double rhs) { if (rhs == 0) throw; cout << lhs / rhs << endl; } }; // 给用户使用的类,包含某个策略 class Calculator { public: Calculator(const char type) { // 利用工厂模式实例化策略 switch (type) { case '+': strategy = new StrategyAdd(); break; case '-': strategy = new StrategySub(); break; case '*': strategy = new StrategyMul(); break; case '/': strategy = new StrategyDiv(); break; default: throw runtime_error("Invalid strategy!"); break; } } ~Calculator() { delete strategy; // 别忘记删除指针 } // 该函数调用具体策略中的算法 void Calculate(const double lhs, const double rhs) { strategy->Algorithm(lhs, rhs); } private: Strategy *strategy; // 保存策略的指针 }; int main() { Calculator add('+'); Calculator sub('-'); Calculator mul('*'); Calculator div('/'); add.Calculate(10, 20); sub.Calculate(30, 40); mul.Calculate(11, 11); div.Calculate(100, 8); system("pause"); return 0; }
原文地址:http://blog.csdn.net/nestler/article/details/37755703