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
| #include <iostream> #include <memory>
class CalculationStrategy { public: virtual ~CalculationStrategy() = default; virtual double calculate(double a, double b) = 0; };
class AddStrategy : public CalculationStrategy { public: double calculate(double a, double b) override { return a + b; } };
class SubtractStrategy : public CalculationStrategy { public: double calculate(double a, double b) override { return a - b; } };
class MultiplyStrategy : public CalculationStrategy { public: double calculate(double a, double b) override { return a * b; } };
class DivideStrategy : public CalculationStrategy { public: double calculate(double a, double b) override { if (b != 0) { return a / b; } throw std::invalid_argument("除数不能为零"); } };
class Calculator { private: std::unique_ptr<CalculationStrategy> strategy_;
public: explicit Calculator(std::unique_ptr<CalculationStrategy> strategy) : strategy_(std::move(strategy)) {}
void setStrategy(std::unique_ptr<CalculationStrategy> strategy) { strategy_ = std::move(strategy); }
double execute(double a, double b) { if (strategy_) { return strategy_->calculate(a, b); } throw std::runtime_error("未设置计算策略"); } };
int main() { Calculator calculator(std::make_unique<AddStrategy>()); std::cout << "10 + 5 = " << calculator.execute(10, 5) << std::endl; calculator.setStrategy(std::make_unique<SubtractStrategy>()); std::cout << "10 - 5 = " << calculator.execute(10, 5) << std::endl; calculator.setStrategy(std::make_unique<MultiplyStrategy>()); std::cout << "10 * 5 = " << calculator.execute(10, 5) << std::endl; calculator.setStrategy(std::make_unique<DivideStrategy>()); std::cout << "10 / 5 = " << calculator.execute(10, 5) << std::endl;
return 0; }
|