Java 的设计模式有哪些|23种经典模式详解与实战指南
〔一〕设计模式的起源与核心价值
设计模式(Design Patterns)是面向对象软件设计中被反复使用、多数人知晓的、经过分类编目的代码设计经验总结。1994年,GoF(Gang of Four)在《设计模式:可复用面向对象软件的基础》一书中系统提出了23种经典设计模式,奠定了现代软件工程的基石。
在Java开发中,设计模式不仅是解决常见问题的模板,更是沟通开发团队的“通用语言”。熟练掌握设计模式,意味着开发者能快速理解他人代码结构、高效参与大型项目协作,并在架构演进中做出更合理的决策。
需要特别指出的是:设计模式不是强制执行的规范,而是经验提炼的**指导原则**。盲目套用反而可能导致过度设计、性能下降或维护困难。正如Martin Fowler所言:“任何傻瓜都能写出计算机能理解的代码。真正优秀的程序员写出的是人能读懂的代码。”
当前主流Java框架(如Spring、Dubbo、MyBatis)中大量运用了设计模式。例如Spring的单例Bean依赖**单例模式**,事务传播机制基于**责任链模式**,AOP代理实现则融合了**代理模式**与**装饰器模式**。深入理解这些模式,是读懂企业级框架源码的关键钥匙。
⚡设计模式的三大核心原则
- 开闭原则(Open-Closed Principle):对扩展开放,对修改关闭——新增功能时尽量不修改已有代码
- 依赖倒置原则(Dependency Inversion Principle):高层模块不应依赖低层模块,二者都应依赖抽象
- 接口隔离原则(Interface Segregation Principle):客户端不应被迫依赖其不使用的接口
值得注意的是,2023年Stack Overflow开发者调查中,78.6%的Java开发者表示在工作中使用过至少3种设计模式,其中**单例模式**(67.2%)、**工厂模式**(52.8%)、**观察者模式**(41.3%)位列前三。这充分说明:掌握设计模式已从“加分项”转变为Java工程师的**必备核心能力**。
〔二〕设计模式的完整分类体系
根据用途与职责,设计模式被划分为三大类共23种,每类解决特定维度的设计问题:
| 类别 | 核心职责 | 包含模式 | 典型应用场景 |
|---|---|---|---|
| 创建型模式 | 对象创建机制 | 单例、工厂方法、抽象工厂、建造者、原型 | 对象创建逻辑复杂、需解耦创建与使用 |
| 结构型模式 | 类与对象的组合 | 适配器、装饰器、代理、桥接、组合、外观、享元 | 系统扩展性需求、接口统一、资源复用 |
| 行为型模式 | 对象间的职责分配 | 策略、模板方法、观察者、迭代器、责任链、命令、备忘录、状态、访问者、中介者、解释器 | 算法封装、事件处理、状态管理、行为解耦 |
特别提醒:初学者常误以为“设计模式越多越好”,实则不然。过度使用模式会导致代码冗余、调试困难。例如在简单工具类中强行使用单例模式,反而增加内存管理负担;在小型项目中滥用工厂模式,会使代码层次冗余。**模式选择应遵循“恰到好处”原则**——仅在解决特定问题时引入。
〔小贴士〕模式选择黄金法则
当遇到以下信号时,才考虑引入设计模式:
• 需频繁修改创建逻辑且影响多处业务代码
• 对象间存在强耦合导致单元测试困难
• 系统需支持多种算法动态切换
• 事件通知机制需要解耦发布者与订阅者
〔三〕创建型模式详解与代码实战
创建型模式关注对象的创建过程,核心目标是**将对象的创建与使用分离**,提升系统的灵活性与可维护性。以下按使用频率排序详解:
3.1 单例模式(Singleton Pattern)
确保某类仅有一个实例,并提供全局访问点。Java中常见实现方式有五种,各具优劣:
饿汉式:类加载即初始化
优点:线程安全、实现简单;缺点:可能造成内存浪费
public class SingletonEager {
private static final SingletonEager INSTANCE = new SingletonEager();
private SingletonEager() {}
public static SingletonEager getInstance() {
return INSTANCE;
}
}
适用场景:实例创建开销小、必被使用的场景(如配置管理器)
懒汉式:按需创建
优点:节省内存;缺点:需处理线程安全问题
public class SingletonLazy {
private static SingletonLazy instance;
private SingletonLazy() {}
public static synchronized SingletonLazy getInstance() {
if (instance == null) {
instance = new SingletonLazy();
}
return instance;
}
}
注意:synchronized影响性能,高并发场景需用双重检查锁
双重检查锁(DCL):兼顾性能与安全
public class SingletonDCL {
private volatile static SingletonDCL instance;
private SingletonDCL() {}
public static SingletonDCL getInstance() {
if (instance == null) {
synchronized (SingletonDCL.class) {
if (instance == null) {
instance = new SingletonDCL();
}
}
}
return instance;
}
}
关键点:volatile防止指令重排序,确保多线程可见性
枚举单例:《Effective Java》推荐方案
public enum SingletonEnum {
INSTANCE;
public void doSomething() {
// 业务逻辑
}
}
优势:天然防止反射与反序列化攻击,代码最简洁
容器单例:Spring的实现基础
public class SingletonContainer {
private static final Map container = new ConcurrentHashMap<>();
public static void register(String key, Object obj) {
container.put(key, obj);
}
public static Object getInstance(String key) {
return container.get(key);
}
}
典型应用:Spring的BeanFactory通过容器管理单例Bean
3.2 工厂模式家族
工厂模式将对象创建过程封装,实现**解耦**。核心分为三类:
3.2.1 简单工厂(Simple Factory)
非23种模式之一,但实际开发中最常用。通过静态方法创建对象:
public class CarFactory {
public static Car createCar(String type) {
switch (type) {
case "sedan": return new Sedan();
case "suv": return new SUV();
default: throw new IllegalArgumentException("Invalid type");
}
}
}
问题:违反开闭原则,新增车型需修改工厂类
3.2.2 工厂方法(Factory Method)
定义创建接口,让子类决定实例化哪个类
interface CarFactory {
Car createCar();
}
class SedanFactory implements CarFactory {
public Car createCar() { return new Sedan(); }
}
class SUVFactory implements CarFactory {
public Car createCar() { return new SUV(); }
}
优势:新增车型只需添加新工厂类,符合开闭原则
3.2.3 抽象工厂(Abstract Factory)
创建一组相关或相互依赖的对象(如UI主题)
interface UIAbstractFactory {
Button createButton();
TextField createTextField();
}
class LightThemeFactory implements UIAbstractFactory {
public Button createButton() { return new LightButton(); }
public TextField createTextField() { return new LightTextField(); }
}
class DarkThemeFactory implements UIAbstractFactory {
public Button createButton() { return new DarkButton(); }
public TextField createTextField() { return new DarkTextField(); }
}
典型应用:Java Swing的UIManager、Spring的DataSource创建
3.3 建造者模式(Builder Pattern)
将复杂对象的构建与其表示分离,使同样的构建过程可创建不同表示。
public class Computer {
private final String cpu;
private final int ram;
private final String disk;
private Computer(Builder builder) {
this.cpu = builder.cpu;
this.ram = builder.ram;
this.disk = builder.disk;
}
public static class Builder {
private String cpu;
private int ram;
private String disk;
public Builder cpu(String cpu) { this.cpu = cpu; return this; }
public Builder ram(int ram) { this.ram = ram; return this; }
public Builder disk(String disk) { this.disk = disk; return this; }
public Computer build() {
return new Computer(this);
}
}
}
优势:避免构造函数参数爆炸,提升代码可读性
Spring中JdbcTemplate、RedisTemplate均采用此模式
3.4 原型模式(Prototype Pattern)
通过复制现有对象创建新对象,适用于创建成本高的对象。
public class Document implements Cloneable {
private String title;
private List contents;
@Override
protected Object clone() throws CloneNotSupportedException {
Document doc = (Document) super.clone();
doc.contents = new ArrayList<>(this.contents); // 深拷贝
return doc;
}
}
注意:浅拷贝仅复制引用,深拷贝需递归复制对象
〔四〕结构型模式:构建灵活的系统骨架
结构型模式关注如何组合类和对象以形成更大的结构,核心目标是**提升系统扩展性与复用性**。
4.1 适配器模式(Adapter Pattern)
将一个类的接口转换成客户希望的另一个接口,解决接口不兼容问题。
// 目标接口
interface Target { void request(); }
// 被适配类
class Adaptee { public void specificRequest() { System.out.println("Adaptee"); } }
// 类适配器(继承)
class ClassAdapter extends Adaptee implements Target {
public void request() { specificRequest(); }
}
// 对象适配器(组合)【推荐】
class ObjectAdapter implements Target {
private Adaptee adaptee;
public ObjectAdapter(Adaptee adaptee) { this.adaptee = adaptee; }
public void request() { adaptee.specificRequest(); }
}
典型应用:Java IO流(InputStreamReader)、Spring AOP的MethodInterceptor
4.2 装饰器模式(Decorator Pattern)
动态给对象添加额外职责,比生成子类更灵活。
interface Coffee { String getDescription(); double getCost(); }
class SimpleCoffee implements Coffee {
public String getDescription() { return "Simple Coffee"; }
public double getCost() { return 5.0; }
}
abstract class CoffeeDecorator implements Coffee {
protected Coffee decoratedCoffee;
public CoffeeDecorator(Coffee coffee) { this.decoratedCoffee = coffee; }
}
class MilkDecorator extends CoffeeDecorator {
public MilkDecorator(Coffee coffee) { super(coffee); }
public String getDescription() { return decoratedCoffee.getDescription() + ", Milk"; }
public double getCost() { return decoratedCoffee.getCost() + 1.5; }
}
优势:避免类爆炸(Milk+Sugar=新类),支持动态组合
典型应用:Java IO流(BufferedInputStream)、Servlet Filter链
4.3 代理模式(Proxy Pattern)
为其他对象提供一种代理以控制对这个对象的访问。
interface Service { void doSomething(); }
class RealService implements Service {
public void doSomething() { System.out.println("Real work"); }
}
class ProxyService implements Service {
private Service service = new RealService();
public void doSomething() {
System.out.println("Before: logging");
service.doSomething();
System.out.println("After: cleanup");
}
}
代理类型:
• 远程代理(RMI)
• 虚拟代理(延迟加载)
• 安全代理(权限控制)
• 防火墙代理(网络防护)
Spring AOP的底层实现即基于代理模式(JDK动态代理/CGLIB)
4.4 外观模式(Facade Pattern)
为子系统中的一组接口提供一个一致的界面,简化客户端使用。
class CPU { public void startup() { System.out.println("CPU start"); } }
class Memory { public void startup() { System.out.println("Memory start"); } }
class Disk { public void startup() { System.out.println("Disk start"); } }
class ComputerFacade {
private CPU cpu = new CPU();
private Memory memory = new Memory();
private Disk disk = new Disk();
public void startup() {
cpu.startup();
memory.startup();
disk.startup();
System.out.println("Computer ready");
}
}
典型应用:JDBC的DriverManager、Spring的JdbcTemplate
〔五〕行为型模式:解耦对象间的交互
行为型模式关注对象间的职责分配与通信,核心目标是**实现行为解耦与算法封装**。
5.1 策略模式(Strategy Pattern)
定义一系列算法,将每个算法封装起来,并使它们可互换。
interface DiscountStrategy { double calculate(double price); }
class NormalStrategy implements DiscountStrategy {
public double calculate(double price) { return price; }
}
class VIPStrategy implements DiscountStrategy {
public double calculate(double price) { return price * 0.9; }
}
class Order {
private DiscountStrategy strategy;
public void setStrategy(DiscountStrategy strategy) {
this.strategy = strategy;
}
public double finalPrice(double price) {
return strategy.calculate(price);
}
}
优势:消除大量if-else,支持运行时切换算法
典型应用:Java Collections.sort的Comparator、Spring的TransactionStrategy
5.2 观察者模式(Observer Pattern)
定义对象间的一对多依赖关系,当一个对象状态改变时,所有依赖者都收到通知。
interface Observer { void update(String message); }
interface Subject { void registerObserver(Observer o); void notifyObservers(String msg); }
class NewsAgency implements Subject {
private List observers = new ArrayList<>();
public void registerObserver(Observer o) { observers.add(o); }
public void notifyObservers(String msg) {
observers.forEach(o -> o.update(msg));
}
public void publishNews(String news) {
System.out.println("Publishing: " + news);
notifyObservers(news);
}
}
class SMSObserver implements Observer {
public void update(String msg) { System.out.println("SMS: " + msg); }
}
Java内置支持:java.util.Observer(已过时)→ java.util.Observable
现代替代方案:Spring的ApplicationEventPublisher、ReactiveX
5.3 责任链模式(Chain of Responsibility)
将请求的发送者和接收者解耦,使多个对象都有机会处理请求。
abstract class Handler {
protected Handler next;
public Handler setNext(Handler next) {
this.next = next;
return next;
}
public abstract void handleRequest(Request request);
}
class AuthHandler extends Handler {
public void handleRequest(Request request) {
if (request.getType() == RequestType.LOGIN) {
System.out.println("Authenticating...");
} else {
next.handleRequest(request);
}
}
}
class LogHandler extends Handler {
public void handleRequest(Request request) {
System.out.println("Logging request...");
}
}
典型应用:Servlet Filter链、Dubbo的Filter链、Spring Security
5.4 模板方法模式(Template Method)
定义一个操作中的算法骨架,而将某些步骤延迟到子类中。
abstract class Beverage {
final void prepareRecipe() {
boilWater();
brew();
pourInCup();
addCondiments();
}
abstract void brew();
abstract void addCondiments();
void boilWater() { System.out.println("Boiling water"); }
void pourInCup() { System.out.println("Pouring into cup"); }
}
class Coffee extends Beverage {
void brew() { System.out.println("Dripping coffee through filter"); }
void addCondiments() { System.out.println("Adding sugar and milk"); }
}
优势:复用公共流程,子类只关注差异点
典型应用:JdbcTemplate的execute方法、Servlet的doGet/doPost
〔六〕设计模式在企业级开发中的实战应用
6.1 Spring框架中的模式应用
Spring几乎集成了所有设计模式的精华:
- 单例模式:Bean默认作用域为singleton
- 工厂模式:BeanFactory/ApplicationContext
- 代理模式:AOP底层实现(JDK动态代理/CGLIB)
- 模板方法:JdbcTemplate、RestTemplate
- 观察者模式:ApplicationEvent机制
- 适配器模式:HandlerAdapter处理不同Controller
6.2 MyBatis中的模式应用
MyBatis是设计模式的教科书级应用:
- 建造者模式:SqlSessionFactoryBuilder
- 代理模式:MapperProxy动态代理SQL执行
- 责任链模式:Interceptor拦截器链
- 装饰器模式:Cache的装饰器链(LruCache、ScheduledCache等)
〔最佳实践〕模式选择决策树
- 需要控制对象创建? → 创建型模式
- 需要组合类与对象? → 结构型模式
- 需要分配对象间职责? → 行为型模式
- 是否存在“创建复杂对象”需求? → 建造者/工厂
- 是否需解耦请求发送与处理? → 责任链/命令
- 是否需动态切换算法? → 策略/状态
6.3 高并发场景下的模式优化
在高并发系统中,设计模式需结合性能考量:
- 单例模式:优先使用枚举或双重检查锁
- 工厂模式:结合对象池减少GC压力
- 观察者模式:使用异步通知避免阻塞主线程
- 策略模式:配合策略注册中心实现热插拔
〔八〕总结:构建可维护的Java系统
掌握设计模式不是为了在面试中炫技,而是为了:
- 降低代码耦合度,提升系统可维护性
- 复用成熟解决方案,避免重复造轮子
- 与团队建立统一设计语言,提升协作效率
- 读懂主流框架源码,突破技术瓶颈
建议学习路径:
① 理解23种模式的**动机与适用场景**
② 在小型项目中尝试应用1-2种模式
③ 阅读Spring/MyBatis源码验证理解
④ 参与代码评审时关注模式使用合理性
⑤ 持续优化:根据业务变化调整模式应用
最后强调:**模式是经验的结晶,而非教条的枷锁。** 真正的高手不在于记住多少模式名称,而在于能根据业务场景选择最合适的解决方案——有时最简单的if-else,反而是最好的设计。
〔推荐学习资源〕
- 《设计模式:可复用面向对象软件的基础》(GoF经典)
- 《Head First设计模式》(图解版,适合初学者)
- 《Spring源码深度解析》(实战解读)
- GitHub开源项目:Spring Framework、MyBatis源码
- 视频课程:极客时间《设计模式之美》