策略模式(Strategy)是一种行为型设计模式,它允许在运行时选择算法的行为。通过将算法封装成独立的类,使得算法可以互换使用,而不影响使用算法的客户端代码。
特点
1、算法封装:将一系列算法封装在独立的策略类中。
2、客户端独立:客户端代码不需要了解具体的算法实现,依赖于策略接口。
3、动态切换:在运行时可以根据需要选择或切换具体的策略。
适用场景
1、当有多个相关的算法可以互换使用时。
2、客户端希望选择某种算法而不需要知道其内部实现。
3、需要使用算法的上下文不想被算法的变化所影响。
示例
假设我们有一个支付系统,可以使用不同的支付方式(如信用卡、PayPal、比特币等)。我们可以使用策略模式来实现。
//g++ -o test main.cpp
#include <iostream>
#include <memory>
// 支付策略接口
class PaymentStrategy {
public:
virtual void pay(int amount) = 0;
virtual ~PaymentStrategy() = default;
};
// 具体策略:信用卡支付
class CreditCardPayment : public PaymentStrategy {
public:
void pay(int amount) override {
std::cout << "Paid " << amount << " using Credit Card." << std::endl;
}
};
// 具体策略:PayPal支付
class PayPalPayment : public PaymentStrategy {
public:
void pay(int amount) override {
std::cout << "Paid " << amount << " using PayPal." << std::endl;
}
};
// 具体策略:比特币支付
class BitcoinPayment : public PaymentStrategy {
public:
void pay(int amount) override {
std::cout << "Paid " << amount << " using Bitcoin." << std::endl;
}
};
// 上下文类
class ShoppingCart {
private:
std::unique_ptr<PaymentStrategy> paymentStrategy;
public:
void setPaymentStrategy(PaymentStrategy* strategy) {
paymentStrategy.reset(strategy);
}
void checkout(int amount) {
if (paymentStrategy) {
paymentStrategy->pay(amount);
} else {
std::cout << "No payment method selected!" << std::endl;
}
}
};
// 客户端代码
int main() {
ShoppingCart cart;
// 使用信用卡支付
cart.setPaymentStrategy(new CreditCardPayment());
cart.checkout(100);
// 使用PayPal支付
cart.setPaymentStrategy(new PayPalPayment());
cart.checkout(200);
// 使用比特币支付
cart.setPaymentStrategy(new BitcoinPayment());
cart.checkout(300);
return 0;
}
在这个例子中,PaymentStrategy 接口定义了支付方法,具体的支付方式(如 CreditCardPayment、PayPalPayment 和 BitcoinPayment)实现了该接口。ShoppingCart 类可以根据需要动态设置支付策略,灵活应对不同的支付方式。