跳到正文
Joeplover
学习笔记·2026-06-20·约 3 分钟阅读

设计模式学习笔记:策略、观察者、工厂

用全新场景学习三种核心设计模式——策略模式、观察者模式和工厂模式,包括它们的区别、适用场景和代码示例。

蓝图设计

设计模式学习笔记:策略、观察者、工厂

项目背景

设计模式是软件开发中常见问题的通用解决方案。这份笔记记录了策略模式、观察者模式、工厂模式、适配器模式的学习心得和实践经验。

策略模式

是什么

把 if-else 中"不同的做法"拆成独立的策略类,调用方按需选择。

代码结构

// 策略接口
interface PaymentStrategy {
    void pay(double amount);
}

// 具体策略
class AlipayStrategy implements PaymentStrategy {
    void pay(double amount) {
        // 支付宝支付逻辑
    }
}
class WechatPayStrategy implements PaymentStrategy {
    void pay(double amount) {
        // 微信支付逻辑
    }
}

// 上下文
class PaymentContext {
    private PaymentStrategy strategy;

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

    void executePayment(double amount) {
        strategy.pay(amount);
    }
}

之前写代码的逻辑:if(type=="alipay"){...} else if(type=="wechat"){...}。加一个支付方式就要改 if-else。策略模式把每种支付封装成独立类,加新方式只需新增类,不用动已有代码。

和模板方法模式的区别

  • 策略模式:更换的是整个算法,调用方去选择
  • 模板方法:只调某个步骤,算法骨架固定

实际项目应用

在 BigGraph 项目中,不同文档类型的解析策略(PDF 解析器、Word 解析器、TXT 解析器)就是用策略模式组织的,各自实现 DocumentParser 接口。

观察者模式

是什么

一对多的依赖关系:一个 Subject 状态变化时,所有依赖它的 Observer 自动收到通知。

核心结构

interface Observer {
    void update(String message);
}

class Subject {
    private List<Observer> observers = new ArrayList<>();

    void attach(Observer o) { observers.add(o); }
    void detach(Observer o) { observers.remove(o); }

    void notifyObservers(String message) {
        for (Observer o : observers) {
            o.update(message);
        }
    }
}

Subject 不依赖具体的 Observer,只依赖 Observer 接口,这就是依赖倒置。

实际应用场景

  • 事件驱动架构(Spring 的 ApplicationEvent/Listener)
  • 消息队列(RabbitMQ 的发布订阅模式本质就是观察者)
  • GUI 事件监听(按钮点击事件)

工厂模式

三种变体

简单工厂: 一个静态方法根据参数返回不同对象(不是严格的设计模式,但最常用)

public static DocumentParser createParser(String type) {
    return switch(type) {
        case "pdf" -> new PdfParser();
        case "word" -> new WordParser();
        default -> throw new IllegalArgumentException();
    };
}

工厂方法: 每个子类决定创建什么对象,把对象的创建延迟到子类

抽象工厂: 生产一组相关的产品对象(比如 GUI 组件工厂——Windows 工厂生产 Windows 按钮、Windows 文本框;Mac 工厂生产 Mac 按钮、Mac 文本框)

适配器模式

是什么

两个类的接口不兼容时,加一层适配器来转换。

// 旧系统接口
interface OldPaymentSystem {
    void processPayment(Map<String, String> params);
}

// 新系统接口
interface NewPaymentSystem {
    PaymentResult pay(String orderId, double amount);
}

// 适配器:把新接口转成旧接口
class PaymentAdapter implements OldPaymentSystem {
    private NewPaymentSystem newSystem;

    void processPayment(Map<String, String> params) {
        String orderId = params.get("orderId");
        double amount = Double.parseDouble(params.get("amount"));
        newSystem.pay(orderId, amount);
    }
}

适配器在不修改双方代码的前提下完成对接,适用于对接旧系统或第三方库。

总结

设计模式是概念工具而不是代码模板。合适的模式用在合适的场景才有价值,过度使用反而增加复杂度。实际项目中,策略模式最常用(消除 if-else),观察者模式最常见(事件驱动),工厂模式处处都有(Spring IoC 本身就是大工厂)。