一、设计模式三大分类总览
- 创建型模式(5种)
核心目标:对象创建的优化与解耦
单例模式(Singleton)
工厂模式(Factory)
抽象工厂模式(Abstract Factory)
建造者模式(Builder)
原型模式(Prototype)
- 结构型模式(7种)
核心目标:类与对象组合的灵活架构
适配器模式(Adapter)
装饰器模式(Decorator)
代理模式(Proxy)
外观模式(Facade)
桥接模式(Bridge)
组合模式(Composite)
享元模式(Flyweight)
- 行为型模式(11种)
核心目标:对象间的交互与职责分配
观察者模式(Observer)
策略模式(Strategy)
命令模式(Command)
责任链模式(Chain of Responsibility)
状态模式(State)
模板方法模式(Template Method)
迭代器模式(Iterator)
中介者模式(Mediator)
备忘录模式(Memento)
访问者模式(Visitor)
解释器模式(Interpreter)
二、创建型模式深度解析
1. 单例模式(Singleton)——对象创建的终极控制
核心特征:全局唯一实例 + 延迟初始化 + 线程安全
演进式实现对比
// 1. 饿汉式(线程安全但立即加载)
public class EagerSingleton {private static final EagerSingleton INSTANCE = new EagerSingleton();private EagerSingleton() {}public static EagerSingleton getInstance() { return INSTANCE; }
}// 2. 双重校验锁(DCL)实现
public class DCLSingleton {private static volatile DCLSingleton instance; // volatile禁止指令重排序private DCLSingleton() {}public static DCLSingleton getInstance() {if (instance == null) { // 第一次检查synchronized (DCLSingleton.class) { // 锁粒度控制if (instance == null) { // 第二次检查instance = new DCLSingleton(); // 安全发布}}}return instance;}
}// 3. 枚举实现(《Effective Java》推荐方式)
public enum EnumSingleton {INSTANCE;public void businessMethod() { /*...*/ }
}
技术深挖:
-
volatile关键字:防止JVM指令重排序导致对象未初始化完成就被使用(JVM规范允许的优化)
-
类加载机制:枚举实现利用类加载的线程安全性保证单例
-
序列化攻击防御:枚举天然防反射和序列化破坏,普通实现需重写readResolve()
典型应用场景:
// Java原生API中的单例
Runtime runtime = Runtime.getRuntime(); // JVM运行时环境单例
Desktop desktop = Desktop.getDesktop(); // 桌面操作单例
2. 工厂模式(Factory)——对象创建的工业化革命
模式演进三阶段:
简单工厂 → 工厂方法 → 抽象工厂
工厂方法模式(Factory Method)
// 产品接口
public interface DatabaseConnection {void connect();
}// 具体产品
public class MySQLConnection implements DatabaseConnection {@Override public void connect() { System.out.println("MySQL connected"); }
}// 抽象工厂
public abstract class ConnectionFactory {public abstract DatabaseConnection createConnection();// 模板方法public void initializeConnection() {DatabaseConnection conn = createConnection();conn.connect();// 公共初始化逻辑...}
}// 具体工厂
public class MySQLFactory extends ConnectionFactory {@Overridepublic DatabaseConnection createConnection() {return new MySQLConnection();}
}
Spring框架中的高级应用:
<!-- Bean配置工厂方法 -->
<bean id="mysqlFactory" class="com.example.MySQLFactory"/>
<bean id="connection" factory-bean="mysqlFactory" factory-method="createConnection"/>
三、结构型模式实战精讲
1. 适配器模式(Adapter)——接口转换的艺术
两种实现方式对比:
类型 | 实现方式 | 适用场景 | Java示例 |
---|---|---|---|
类适配器 | 继承被适配类 | 需要复用现有类代码 | 较少使用 |
对象适配器 | 组合被适配对象 | 更灵活的解耦方式 | InputStreamReader |
JDK中的经典实现:
// 将字节流转换为字符流
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
现代Java中的函数式适配:
// 使用Lambda适配旧接口
Runnable legacyTask = () -> System.out.println("Old task");
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.submit(legacyTask::run);
2. 装饰器模式(Decorator)——动态增强的利器
模式结构:
Component↑ ↑ConcreteComponent ← Decorator↑ConcreteDecoratorA
Java IO流的装饰器体系:
// 多层装饰示例
InputStream in = new FileInputStream("data.txt");
in = new BufferedInputStream(in); // 添加缓冲功能
in = new GZIPInputStream(in); // 添加压缩解压功能
自定义装饰器实现:
public class CryptoInputStream extends FilterInputStream {private Cipher cipher;public CryptoInputStream(InputStream in, SecretKey key) throws GeneralSecurityException {super(in);cipher = Cipher.getInstance("AES");cipher.init(Cipher.DECRYPT_MODE, key);}@Overridepublic int read(byte[] b, int off, int len) throws IOException {int bytesRead = super.read(b, off, len);if (bytesRead > 0) {try {cipher.doFinal(b, off, bytesRead); // 解密处理} catch (IllegalBlockSizeException | BadPaddingException e) {throw new IOException("Decryption failed", e);}}return bytesRead;}
}
四、行为型模式核心剖析
1. 观察者模式(Observer)——事件驱动的基石
Java内置实现演进:
// 传统实现(已过时但仍有参考价值)
public class Observable {private boolean changed = false;private Vector<Observer> observers;public synchronized void addObserver(Observer o) { /*...*/ }public void notifyObservers(Object arg) {// 同步通知逻辑...}
}// 现代实现(推荐)
public class PropertyChangeSupport {public void addPropertyChangeListener(PropertyChangeListener listener) { /*...*/ }public void firePropertyChange(String propertyName, Object oldValue, Object newValue) {// 事件派发...}
}
响应式编程扩展(RxJava示例):
Observable<String> observable = Observable.create(emitter -> {emitter.onNext("Event 1");emitter.onNext("Event 2");emitter.onComplete();
});observable.subscribe(event -> System.out.println("Received: " + event),error -> System.err.println("Error: " + error),() -> System.out.println("Completed")
);
2. 策略模式(Strategy)——算法族的自由切换
Lambda表达式带来的革新:
// 传统实现
public interface ValidationStrategy {boolean execute(String s);
}public class IsNumeric implements ValidationStrategy {@Overridepublic boolean execute(String s) {return s.matches("\\d+");}
}// Lambda实现
ValidationStrategy numericStrategy = s -> s.matches("\\d+");
ValidationStrategy lowerCaseStrategy = s -> s.matches("[a-z]+");// 上下文使用
public class Validator {private ValidationStrategy strategy;public Validator(ValidationStrategy v) { this.strategy = v; }public boolean validate(String s) { return strategy.execute(s); }
}
Java集合框架的典型应用:
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
Collections.sort(names, (a, b) -> b.compareTo(a)); // 策略注入
五、Java特有模式深度探讨
1. 空对象模式(Null Object)——防御式编程的优雅解决方案
完整实现示例:
public interface Logger {void log(String message);
}public class ConsoleLogger implements Logger {@Overridepublic void log(String message) {System.out.println(message);}
}public class NullLogger implements Logger {@Overridepublic void log(String message) {// 静默处理}
}// 客户端使用
public class PaymentService {private Logger logger = new NullLogger(); // 默认安全public void setLogger(Logger logger) {this.logger = Objects.requireNonNullElse(logger, new NullLogger());}public void processPayment() {logger.log("Payment started");// 业务逻辑...}
}
2. 不可变对象模式(Immutable Object)——并发安全的终极形态
构建不可变类的五大铁律:
- 所有字段final修饰
- 类声明为final
- 不暴露可变引用
- 不提供setter方法
- 构造器完全初始化
深度防御示例:
public final class ImmutablePerson {private final String name;private final Date birthDate; // Date本身可变public ImmutablePerson(String name, Date birthDate) {this.name = name;// 防御性拷贝this.birthDate = new Date(birthDate.getTime());}public Date getBirthDate() {// 返回拷贝对象return new Date(birthDate.getTime());}
}
六、模式应用黄金法则
1. 模式选择决策树
是否需要控制对象创建? → 创建型模式├─ 需要全局唯一实例 → 单例├─ 需要复杂构造过程 → 建造者└─ 需要灵活的产品族 → 抽象工厂是否需要重组对象结构? → 结构型模式├─ 接口不兼容 → 适配器├─ 需要透明扩展 → 装饰器└─ 控制对象访问 → 代理是否需要协调对象行为? → 行为型模式├─ 事件通知机制 → 观察者├─ 算法动态切换 → 策略└─ 流程标准化 → 模板方法
2. 模式反模式警示
- 单例滥用:导致隐藏的依赖关系和测试困难
- 过度装饰:产生过多小对象影响性能
- 观察者泄漏:未及时取消注册导致内存泄漏
- 策略膨胀:大量策略类增加维护成本
七、现代Java中的模式演进
1. Lambda表达式对传统模式的冲击
策略模式简化:
// 传统方式
Arrays.sort(words, new Comparator<String>() {public int compare(String a, String b) {return Integer.compare(a.length(), b.length());}
});// Lambda简化
Arrays.sort(words, (a, b) -> Integer.compare(a.length(), b.length()));
2. 模块化带来的模式变化
服务加载器替代工厂模式:
// META-INF/services/com.example.DatabaseConnection
ServiceLoader<DatabaseConnection> loader = ServiceLoader.load(DatabaseConnection.class);
DatabaseConnection conn = loader.findFirst().orElseThrow();
八、设计模式在Java生态中的典型应用
框架/库 | 核心模式 | 具体实现 |
---|---|---|
Spring | 工厂模式、代理模式、模板方法 | BeanFactory、AOP代理、JdbcTemplate |
Hibernate | 代理模式、工厂模式 | 延迟加载代理、SessionFactory |
JavaFX | 观察者模式、命令模式 | Property绑定、EventHandler |
Netty | 责任链模式、Reactor模式 | ChannelPipeline、EventLoop |