23种设计模式23种设计模式
首页
介绍
  • 单例模式
  • 工厂方法模式
  • 抽象工厂模式
  • 建造者模式
  • 原型模式
  • 适配器模式
  • 桥接模式
  • 组合模式
  • 装饰器模式
  • 外观模式
  • 享元模式
  • 代理模式
  • 责任链模式
  • 命令模式
  • 解释器模式
  • 迭代器模式
  • 中介者模式
  • 备忘录模式
  • 观察者模式
  • 状态模式
  • 策略模式
  • 模板方法模式
  • 访问者模式
🚀 编程指南
首页
介绍
  • 单例模式
  • 工厂方法模式
  • 抽象工厂模式
  • 建造者模式
  • 原型模式
  • 适配器模式
  • 桥接模式
  • 组合模式
  • 装饰器模式
  • 外观模式
  • 享元模式
  • 代理模式
  • 责任链模式
  • 命令模式
  • 解释器模式
  • 迭代器模式
  • 中介者模式
  • 备忘录模式
  • 观察者模式
  • 状态模式
  • 策略模式
  • 模板方法模式
  • 访问者模式
🚀 编程指南
  • 行为型模式

    • 责任链模式 (Chain of Responsibility)
    • 命令模式 (Command)
    • 解释器模式 (Interpreter)
    • 迭代器模式 (Iterator)
    • 中介者模式 (Mediator)
    • 备忘录模式 (Memento)
    • 观察者模式 (Observer)
    • 状态模式 (State)
    • 策略模式 (Strategy)
    • 模板方法模式 (Template Method)
    • 访问者模式 (Visitor)

策略模式 (Strategy)

📖 通俗理解

出行方式选择:

  • 距离近 → 走路
  • 距离中等 → 骑自行车
  • 距离远 → 开车/打车

你可以根据情况自由切换出行策略,而不需要改变出行这件事本身。

策略模式就是:定义一系列算法,把它们一个个封装起来,并且使它们可以互相替换。

🎯 解决什么问题?

避免大量 if-else,让算法可以灵活替换。

// ❌ 没有策略模式
if (type == "alipay") {
    alipayPay();
} else if (type == "wechat") {
    wechatPay();
} else if (type == "bank") {
    bankPay();
}

// ✅ 有策略模式
payStrategy.pay(amount);  // 策略自己知道怎么支付

🌰 生活中的例子

  • 出行方式:走路/骑车/开车/打车
  • 支付方式:微信/支付宝/银行卡
  • 排序算法:冒泡/快排/归并

💻 Java 代码实现

场景:支付策略

/**
 * 策略接口
 */
public interface PayStrategy {
    void pay(double amount);
}

/**
 * 微信支付
 */
public class WechatPay implements PayStrategy {
    @Override
    public void pay(double amount) {
        System.out.println("微信支付: ¥" + amount);
    }
}

/**
 * 支付宝支付
 */
public class AlipayPay implements PayStrategy {
    @Override
    public void pay(double amount) {
        System.out.println("支付宝支付: ¥" + amount);
    }
}

/**
 * 银行卡支付
 */
public class BankCardPay implements PayStrategy {
    @Override
    public void pay(double amount) {
        System.out.println("银行卡支付: ¥" + amount);
    }
}

/**
 * 上下文:收银台
 */
public class Cashier {
    private PayStrategy payStrategy;
    
    public void setPayStrategy(PayStrategy payStrategy) {
        this.payStrategy = payStrategy;
    }
    
    public void checkout(double amount) {
        if (payStrategy == null) {
            throw new IllegalStateException("请选择支付方式");
        }
        payStrategy.pay(amount);
    }
}

使用:

public class Client {
    public static void main(String[] args) {
        Cashier cashier = new Cashier();
        
        // 选择微信支付
        cashier.setPayStrategy(new WechatPay());
        cashier.checkout(100);
        
        // 切换为支付宝
        cashier.setPayStrategy(new AlipayPay());
        cashier.checkout(200);
        
        // 切换为银行卡
        cashier.setPayStrategy(new BankCardPay());
        cashier.checkout(300);
    }
}

输出:

微信支付: ¥100.0
支付宝支付: ¥200.0
银行卡支付: ¥300.0

🔥 策略 + 工厂(消除 if-else)

public class PayStrategyFactory {
    private static Map<String, PayStrategy> strategies = new HashMap<>();
    
    static {
        strategies.put("wechat", new WechatPay());
        strategies.put("alipay", new AlipayPay());
        strategies.put("bank", new BankCardPay());
    }
    
    public static PayStrategy getStrategy(String type) {
        PayStrategy strategy = strategies.get(type);
        if (strategy == null) {
            throw new IllegalArgumentException("不支持的支付方式: " + type);
        }
        return strategy;
    }
}

// 使用
String payType = "wechat";  // 从前端传来
PayStrategy strategy = PayStrategyFactory.getStrategy(payType);
strategy.pay(100);

✅ 适用场景

  1. 有多种算法/策略可供选择
  2. 需要在运行时切换算法
  3. 避免多重条件判断

小结

策略模式:定义算法族,封装起来,可以互相替换。

与状态模式区别:策略是主动切换,状态是自动转换。

👉 下一篇:模板方法模式

Prev
状态模式 (State)
Next
模板方法模式 (Template Method)