策略模式的介绍与实现
策略模式是什么?
策略模式是一种行为型设计模式,它允许你定义一系列算法,将每个算法封装起来,并使他们可以相互替换。
让算法独立于他的调用方而变化。
比如:我们需要根据不同的支付环境去调用不同的支付策略。
一般我们会写if else或者switch
但是有了策略模式,我们可以将每个支付策略封装成一个独立的类,
并通过上下文类来调用不同的策略。
这样就可以在不修改调用方代码的情况下,动态切换支付策略。
实现策略模式
interface PaymentStrategy {
String pay(String orderId, long amount); }
class AlipayStrategy implements PaymentStrategy {
@Override public String pay(String orderId, long amount) { return "Alipay success: order=" + orderId + ", amount=" + amount; } }
class WechatPayStrategy implements PaymentStrategy {
@Override public String pay(String orderId, long amount) { return "WechatPay success: order=" + orderId + ", amount=" + amount; } }
class CashStrategy implements PaymentStrategy {
@Override public String pay(String orderId, long amount) { return "Cash success: order=" + orderId + ", amount=" + amount; } }
class PaymentContext { private PaymentStrategy strategy;
public PaymentContext(PaymentStrategy strategy) { this.strategy = strategy; }
public String executePay(String orderId, long amount) { return strategy.pay(orderId, amount); }
public void setStrategy(PaymentStrategy strategy) { this.strategy = strategy; } }
class PaymentStrategyFactory {
public static PaymentStrategy getStrategy(String channel) { switch (channel) { case "ALIPAY": return new AlipayStrategy(); case "WECHAT": return new WechatPayStrategy(); case "CASH": return new CashStrategy(); default: throw new IllegalArgumentException("Unsupported channel: " + channel); } } }
public class StrategyDemo {
public static void main(String[] args) { PaymentStrategy strategy = PaymentStrategyFactory.getStrategy("ALIPAY"); PaymentContext ctx = new PaymentContext(strategy);
String result = ctx.executePay("ORD123456", 19900); System.out.println(result);
ctx.setStrategy(PaymentStrategyFactory.getStrategy("WECHAT")); String result2 = ctx.executePay("ORD123456", 19900); System.out.println(result2); } }
|