设计模式(Design Patterns)是软件开发中针对常见问题的可复用解决方案,由 Erich Gamma、Richard Helm、Ralph Johnson 和 John Vlissides("GoF 四人组")于 1994 年在《设计模式:可复用面向对象软件的基础》一书中系统化提出。
设计模式的核心定位是 代码设计的最佳实践。它提供了:
// 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;
}
}
// 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();
// 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();
// 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();
}
}
// 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"
// 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!");
// 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);
| 模式 | 分类 | 使用频率 | 典型场景 |
|---|---|---|---|
| 单例模式 | 创建型 | ⭐⭐⭐⭐⭐ | 全局配置、连接池 |
| 工厂模式 | 创建型 | ⭐⭐⭐⭐⭐ | 对象创建、依赖注入 |
| 建造者模式 | 创建型 | ⭐⭐⭐⭐ | 复杂对象构建 |
| 适配器模式 | 结构型 | ⭐⭐⭐⭐⭐ | 接口兼容、遗留系统 |
| 装饰器模式 | 结构型 | ⭐⭐⭐⭐ | 动态扩展功能 |
| 代理模式 | 结构型 | ⭐⭐⭐⭐ | 延迟加载、缓存 |
| 观察者模式 | 行为型 | ⭐⭐⭐⭐⭐ | 事件驱动、发布订阅 |
| 策略模式 | 行为型 | ⭐⭐⭐⭐⭐ | 算法切换、支付方式 |
| 模板方法 | 行为型 | ⭐⭐⭐⭐ | 流程固定、步骤可变 |
| 责任链模式 | 行为型 | ⭐⭐⭐⭐ | 中间件、过滤器 |
| 状态模式 | 行为型 | ⭐⭐⭐ | 订单状态、工作流 |
学习 SOLID 原则、理解设计模式的目的和分类
重点学习:单例、工厂、适配器、观察者、策略、装饰器
学习所有 23 种模式、理解适用场景和权衡
在项目中识别和应用设计模式、重构代码
设计模式是优秀代码的蓝图。
它用 经过验证的解决方案、通用的设计语言、可复用的设计思想 帮助开发者写出更优雅、可维护、可扩展的代码。设计模式是开发者从初级走向高级的必经之路。
掌握设计模式,意味着你能 写出更好的代码、更高效地沟通设计方案、更快地解决复杂问题。
"设计模式是优秀程序员的共同语言。" 📐