返回主页 学习路径
设计模式
可复用 · 可扩展 · 优雅代码
设计模式(Design Patterns)是软件开发中针对常见问题的可复用解决方案,由 Erich Gamma、Richard Helm、Ralph Johnson 和 John Vlissides("GoF 四人组")于 1994 年在《设计模式:可复用面向对象软件的基础》一书中系统化提出。设计模式不是具体的代码,而是经过验证的、可复用的设计方案,帮助开发者写出更优雅、可维护、可扩展的代码。掌握设计模式是开发者从初级走向高级的必经之路。
开发者进阶必修 · 代码艺术
📅 诞生时间1994年 · GoF 四人组
🧩 类型软件设计方法论
📊 分类设计模式 · 架构模式
⚡性能
8/10
📦生态
10/10
🧠易用
6/10
🚀扩展性
8/10

📑 本文目录

📌 第一部分:设计模式概览与定位

1.1 定义与全称

设计模式(Design Patterns)是软件开发中针对常见问题的可复用解决方案,由 Erich Gamma、Richard Helm、Ralph Johnson 和 John Vlissides("GoF 四人组")于 1994 年在《设计模式:可复用面向对象软件的基础》一书中系统化提出。

1.2 核心定位

设计模式的核心定位是 代码设计的最佳实践。它提供了:

1.3 三大分类

1.4 设计原则(SOLID)


🏗️ 第二部分:创建型模式(5 种)

2.1 单例模式(Singleton)

// Java 单例模式(双重检查锁)
public class Singleton {
    private static volatile Singleton instance;

    private Singleton() {}

    public static Singleton getInstance() {
        if (instance == null) {
            synchronized (Singleton.class) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}

// PHP 单例模式
class Singleton {
    private static $instance = null;

    private function __construct() {}

    public static function getInstance() {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }
}

2.2 工厂模式(Factory)

// Java 工厂模式
interface Product {
    void use();
}

class ProductA implements Product {
    public void use() { System.out.println("Product A"); }
}

class ProductB implements Product {
    public void use() { System.out.println("Product B"); }
}

class ProductFactory {
    public static Product create(String type) {
        switch (type) {
            case "A": return new ProductA();
            case "B": return new ProductB();
            default: throw new IllegalArgumentException();
        }
    }
}

// 使用
Product p = ProductFactory.create("A");
p.use();

2.3 抽象工厂模式(Abstract Factory)

2.4 建造者模式(Builder)

// Java 建造者模式
public class User {
    private final String name;
    private final int age;
    private final String email;
    private final String phone;

    private User(Builder builder) {
        this.name = builder.name;
        this.age = builder.age;
        this.email = builder.email;
        this.phone = builder.phone;
    }

    public static class Builder {
        private final String name;
        private int age;
        private String email;
        private String phone;

        public Builder(String name) { this.name = name; }

        public Builder age(int age) { this.age = age; return this; }
        public Builder email(String email) { this.email = email; return this; }
        public Builder phone(String phone) { this.phone = phone; return this; }

        public User build() { return new User(this); }
    }
}

// 使用
User user = new User.Builder("Alice")
    .age(30)
    .email("alice@example.com")
    .build();

2.5 原型模式(Prototype)


🔗 第三部分:结构型模式(7 种)

3.1 适配器模式(Adapter)

// Java 适配器模式
interface Target {
    void request();
}

class Adaptee {
    public void specificRequest() {
        System.out.println("Adaptee request");
    }
}

class Adapter implements Target {
    private Adaptee adaptee;

    public Adapter(Adaptee adaptee) {
        this.adaptee = adaptee;
    }

    @Override
    public void request() {
        adaptee.specificRequest();
    }
}

3.2 装饰器模式(Decorator)

// Java 装饰器模式(以咖啡为例)
interface Coffee {
    double cost();
    String description();
}

class SimpleCoffee implements Coffee {
    public double cost() { return 5.0; }
    public String description() { return "Simple Coffee"; }
}

class MilkDecorator implements Coffee {
    private Coffee coffee;

    public MilkDecorator(Coffee coffee) { this.coffee = coffee; }

    public double cost() { return coffee.cost() + 1.5; }
    public String description() { return coffee.description() + ", Milk"; }
}

// 使用
Coffee coffee = new SimpleCoffee();
coffee = new MilkDecorator(coffee);
// cost = 6.5, description = "Simple Coffee, Milk"

3.3 代理模式(Proxy)

3.4 外观模式(Facade)

3.5 桥接模式(Bridge)

3.6 组合模式(Composite)

3.7 享元模式(Flyweight)


🔄 第四部分:行为型模式(11 种)

4.1 观察者模式(Observer)

// Java 观察者模式
interface Observer {
    void update(String message);
}

class User implements Observer {
    private String name;

    public User(String name) { this.name = name; }

    @Override
    public void update(String message) {
        System.out.println(name + " received: " + message);
    }
}

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

    public void subscribe(Observer observer) {
        observers.add(observer);
    }

    public void publish(String news) {
        for (Observer observer : observers) {
            observer.update(news);
        }
    }
}

// 使用
NewsPublisher publisher = new NewsPublisher();
publisher.subscribe(new User("Alice"));
publisher.subscribe(new User("Bob"));
publisher.publish("Breaking News!");

4.2 策略模式(Strategy)

// Java 策略模式
interface PaymentStrategy {
    void pay(int amount);
}

class CreditCardPayment implements PaymentStrategy {
    public void pay(int amount) {
        System.out.println("Paid " + amount + " with Credit Card");
    }
}

class PayPalPayment implements PaymentStrategy {
    public void pay(int amount) {
        System.out.println("Paid " + amount + " with PayPal");
    }
}

class ShoppingCart {
    private PaymentStrategy strategy;

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

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

// 使用
ShoppingCart cart = new ShoppingCart();
cart.setStrategy(new CreditCardPayment());
cart.checkout(100);

4.3 模板方法模式(Template Method)

4.4 命令模式(Command)

4.5 责任链模式(Chain of Responsibility)

4.6 状态模式(State)

4.7 访问者模式(Visitor)

4.8 迭代器模式(Iterator)

4.9 中介者模式(Mediator)

4.10 备忘录模式(Memento)

4.11 解释器模式(Interpreter)


📋 第五部分:常用模式速查表

模式 分类 使用频率 典型场景
单例模式创建型⭐⭐⭐⭐⭐全局配置、连接池
工厂模式创建型⭐⭐⭐⭐⭐对象创建、依赖注入
建造者模式创建型⭐⭐⭐⭐复杂对象构建
适配器模式结构型⭐⭐⭐⭐⭐接口兼容、遗留系统
装饰器模式结构型⭐⭐⭐⭐动态扩展功能
代理模式结构型⭐⭐⭐⭐延迟加载、缓存
观察者模式行为型⭐⭐⭐⭐⭐事件驱动、发布订阅
策略模式行为型⭐⭐⭐⭐⭐算法切换、支付方式
模板方法行为型⭐⭐⭐⭐流程固定、步骤可变
责任链模式行为型⭐⭐⭐⭐中间件、过滤器
状态模式行为型⭐⭐⭐订单状态、工作流

🧠 第六部分:学习建议

1
基础入门

学习 SOLID 原则、理解设计模式的目的和分类

2
掌握核心

重点学习:单例、工厂、适配器、观察者、策略、装饰器

3
深入理解

学习所有 23 种模式、理解适用场景和权衡

4
实战应用

在项目中识别和应用设计模式、重构代码

推荐书籍与资源


🎯 总结升华

设计模式是优秀代码的蓝图。

它用 经过验证的解决方案、通用的设计语言、可复用的设计思想 帮助开发者写出更优雅、可维护、可扩展的代码。设计模式是开发者从初级走向高级的必经之路。

掌握设计模式,意味着你能 写出更好的代码、更高效地沟通设计方案、更快地解决复杂问题

"设计模式是优秀程序员的共同语言。" 📐

🔖 相关标签
#设计模式 #SOLID #面向对象 #架构 #代码质量 #GoF #开发者进阶
📄 本文档为设计模式完整白皮书 · 最后更新于 2026年06月28日