策略模式(Strategy Pattern)是一种行为型设计模式,它允许在运行时选择算法的行为。策略模式的核心思想是将不同的算法封装成独立的策略类,并使这些策略类可以互相替换,从而使客户端代码不依赖于具体的算法,增加了代码的灵活性和可维护性
策略接口(Strategy Interface):定义一组算法的通用接口,通常包含一个或多个方法,这些方法表示不同策略所执行的操作。
具体策略类(Concrete Strategies):实现策略接口,提供具体的算法实现。每个具体策略类代表一种算法或策略的具体实现。
环境类(Context):持有一个策略对象的引用,并提供方法来执行算法。环境类通常包含一个设置策略的方法,以及使用策略来执行操作的方法
例子:
- #include
-
- // 策略接口
- class PaymentStrategy {
- public:
- virtual void pay(int amount) = 0;
- };
-
- // 具体策略类1:信用卡支付
- class CreditCardPayment : public PaymentStrategy {
- private:
- std::string cardNumber;
- std::string name;
-
- public:
- CreditCardPayment(const std::string& cardNumber, const std::string& name)
- : cardNumber(cardNumber), name(name) {}
-
- void pay(int amount) override {
- std::cout << amount << " paid using credit card." << std::endl;
- // 具体的支付逻辑
- }
- };
-
- // 具体策略类2:PayPal支付
- class PayPalPayment : public PaymentStrategy {
- private:
- std::string email;
-
- public:
- PayPalPayment(const std::string& email)
- : email(email) {}
-
- void pay(int amount) override {
- std::cout << amount << " paid using PayPal." << std::endl;
- // 具体的支付逻辑
- }
- };
-
- // 环境类
- class ShoppingCart {
- private:
- PaymentStrategy* paymentStrategy;
-
- public:
- void setPaymentStrategy(PaymentStrategy* strategy) {
- paymentStrategy = strategy;
- }
-
- void checkout(int amount) {
- if (paymentStrategy) {
- paymentStrategy->pay(amount);
- } else {
- std::cout << "Please set a payment strategy before checking out." << std::endl;
- }
- }
- };
-
- int main() {
- // 创建环境对象
- ShoppingCart cart;
-
- // 设置具体策略
- cart.setPaymentStrategy(new CreditCardPayment("1234-5678-9876-5432", "John Doe"));
-
- // 执行支付操作
- cart.checkout(100);
-
- // 切换策略
- cart.setPaymentStrategy(new PayPalPayment("john@example.com"));
-
- // 再次执行支付操作
- cart.checkout(50);
-
- return 0;
- }