30 lines
684 B
C++
30 lines
684 B
C++
/**
|
|
* @name 策略模式
|
|
* @brief: 封装可互换的算法
|
|
* @note 场景:支付方式选择(信用卡/支付宝)、排序算法切换
|
|
*/
|
|
|
|
class PaymentStrategy {
|
|
public:
|
|
virtual void pay(int amount) = 0;
|
|
};
|
|
|
|
class CreditCardStrategy : public PaymentStrategy {
|
|
void pay(int amount) override { /* 信用卡支付逻辑 */ }
|
|
};
|
|
|
|
class PaymentContext {
|
|
PaymentStrategy* strategy;
|
|
public:
|
|
void setStrategy(PaymentStrategy* s) { strategy = s; }
|
|
void executePayment(int amount) { strategy->pay(amount); }
|
|
};
|
|
|
|
// 使用
|
|
int main()
|
|
{
|
|
PaymentContext context;
|
|
context.setStrategy(new CreditCardStrategy());
|
|
context.executePayment(100);
|
|
return 0;
|
|
} |