工厂模式(Factory Pattern) vs 策略模式(Strategy Pattern)


1. 工厂模式(Factory Pattern)

核心思想

​ 将对象创建逻辑与使用逻辑解耦,通过统一的接口创建对象,隐藏具体实现类的实例化过程。

典型场景
// 工厂类
public class AnimalFactory {
public static Animal createAnimal(String type) {
if ("dog".equals(type)) {
return new Dog();
} else if ("cat".equals(type)) {
return new Cat();
}
throw new IllegalArgumentException("未知动物类型");
}
}

// 使用方
Animal animal = AnimalFactory.createAnimal("dog");
animal.sound(); // 输出 "汪汪"
关键特点
  • 解决的问题:对象创建依赖具体类,避免 new 直接实例化。
  • 核心角色
    • 工厂类:封装对象创建逻辑(如 AnimalFactory)。
    • 产品接口:定义对象的统一行为(如 Animal)。
    • 具体产品:实现接口的具体类(如 DogCat)。
  • 适用场景
    • 需要根据不同条件创建不同对象(如配置文件、用户输入)。
    • 对象创建过程复杂(如依赖多个参数或初始化步骤)。
    • 希望隐藏具体实现类,降低耦合。

2. 策略模式(Strategy Pattern)

核心思想

​ 定义一系列算法,封装每个算法,并使它们可以互相替换,让算法的变化独立于客户端。

典型场景
// 策略接口
public interface PaymentStrategy {
void pay(int amount);
}

// 具体策略
public class AlipayStrategy implements PaymentStrategy {
@Override
public void pay(int amount) {
System.out.println("支付宝支付:" + amount);
}
}

public class WechatPayStrategy implements PaymentStrategy {
@Override
public void pay(int amount) {
System.out.println("微信支付:" + amount);
}
}

// 上下文(封装策略)
public class PaymentContext {
private PaymentStrategy strategy;

public void setStrategy(PaymentStrategy strategy) {
this.strategy = strategy;
}

public void executePayment(int amount) {
strategy.pay(amount);
}
}

// 使用方
PaymentContext context = new PaymentContext();
context.setStrategy(new AlipayStrategy());
context.executePayment(100); // 输出 "支付宝支付:100"
关键特点
  • 解决的问题:算法频繁变化或需要动态切换。
  • 核心角色
    • 策略接口:定义算法族的行为(如 PaymentStrategy)。
    • 具体策略:实现接口的具体算法(如 AlipayStrategy)。
    • 上下文(Context):持有策略引用并执行算法(如 PaymentContext)。
  • 适用场景
    • 需要动态切换算法(如支付方式、排序规则)。
    • 避免多重条件判断(如 if-else 嵌套)。
    • 算法需要独立扩展或复用。

3. 总结

  • 工厂模式创建型设计模式,解决对象创建问题,核心是“怎么造对象”

  • 策略模式行为型设计模式,解决算法选择问题,核心是“怎么换行为”

  • 结合使用:通过工厂创建策略对象,既能隔离创建逻辑,又能动态切换算法(常见于企业级代码)。