Java 23种设计模式全解析:从基础到实战的应用指南
设计模式作为软件工程中的通用解决方案,是开发者应对复杂系统设计的核心工具。本文系统梳理Java领域23种经典设计模式,通过场景化案例与代码解析,帮助开发者快速掌握模式精髓。
一、创建型模式(7种)
- 单例模式(Singleton Pattern)
确保一个类只有一个实例,全局访问点
适用场景:数据库连接池、配置管理器
实现方式:双重校验锁/枚举方式
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; }}
封装对象创建逻辑,解耦调用者与具体实现
升级方案:抽象工厂模式支持产品族创建
interface Shape { void draw(); }class Rectangle implements Shape {...}class Circle implements Shape {...}class ShapeFactory { public Shape getShape(String type) { if(type == "circle") return new Circle(); else return new Rectangle(); }}
分步骤构建复杂对象,适合多参数构造场景
典型应用:订单生成、文档组装
class Computer { private String cpu; private String memory; // 私有构造+内部Builder类 public static class Builder { private Computer computer = new Computer(); public Builder setCpu(String cpu) { ... } public Computer build() { return computer; } }}
通过克隆已有实例创建新对象,提升性能
关键方法:clone()方法实现深拷贝
class Sheep implements Cloneable { private String name; public Sheep clone() { try { return (Sheep) super.clone(); } catch(CloneNotSupportedException e) { throw new RuntimeException(e); } }}
复用空闲对象减少创建销毁开销
典型应用:数据库连接池、线程池
class ObjectPool{ private Queue pool = new LinkedList<>(); public T getObject() { if(pool.isEmpty()) return createNewObject(); return pool.poll(); } public void returnObject(T obj) { pool.offer(obj); }}
将集合类封装为独立对象,避免直接暴露集合操作
优势:控制元素添加/删除权限
class UserCollection { private Listusers = new ArrayList<>(); public void addUser(User user) { users.add(user); } public Iterator iterator() { return users.iterator(); }}
将多个简单对象组合成复合对象
适用场景:树形结构、文件系统
interface GraphicComponent { void add(GraphicComponent component); void remove(GraphicComponent component); void display();}class CompositeGraphic implements GraphicComponent {...}
二、结构型模式(7种)
- 适配器模式(Adapter)
接口转换桥梁,解决兼容性问题
两种形式:类适配器(继承)/对象适配器(组合)
interface Target { void request(); }class Adaptee { public void specificRequest() {...} }class Adapter extends Adaptee implements Target { public void request() { specificRequest(); }}
动态扩展对象功能,比继承更灵活
典型应用:IO流包装、UI组件增强
abstract class Decorator implements Component { protected Component component; public Decorator(Component c) { this.component = c; } public void operation() { component.operation(); }}class ConcreteDecorator extends Decorator { public ConcreteDecorator(Component c) { super(c); } public void addedBehavior() {...} public void operation() { super.operation(); addedBehavior(); }}
控制对对象的访问,实现远程/安全/智能访问
四类代理:远程代理/虚拟代理/保护代理/智能引用
interface Image { void display();}class ProxyImage implements Image { private RealImage realImage; private String filename; public void display() { if(realImage == null) realImage = new RealImage(filename); realImage.display(); }}
简化复杂子系统接口,提供统一入口
适用场景:框架API封装、模块间交互
class CPU { void freeze() {...}; ... }class Memory { void load(...) {...}; }class HardDrive { void read(...) {...}; }class ComputerFacade { private CPU cpu; private Memory memory; ... public void startComputer() { cpu.freeze(); memory.load(...); // 启动流程封装 }}
共享重复对象减少内存消耗
典型应用:字体渲染、游戏地图
interface Flyweight { void operation(...);}class FlyweightFactory { private Mappool = new HashMap<>(); public Flyweight getFlyweight(String key) { if(!pool.containsKey(key)) pool.put(key, new ConcreteFlyweight()); return pool.get(key); }}
分离抽象与实现,解除静态耦合
适用场景:跨平台开发、多维度扩展
interface Implementor { void operationImpl();}class Abstraction { protected Implementor imp; public Abstraction(Implementor imp) { this.imp = imp; } public void operation() { imp.operationImpl(); }}class RefinedAbstraction extends Abstraction { public RefinedAbstraction(Implementor imp) { super(imp); } public void operation() { // 扩展功能 super.operation(); }}
树形结构统一处理,父节点与叶子节点一致性
核心接口:add/remove getChild
abstract class Component { public abstract void add(Component c); public abstract void remove(Component c); public abstract void display();}class Leaf extends Component {...}class Composite extends Component { private Listchildren = new ArrayList<>(); public void add(Component c) { children.add(c); } public void display() { for(Component c : children) c.display(); }}
三、行为型模式(9种)
- 策略模式(Strategy)
算法封装可互换,避免条件判断爆炸
适用场景:支付方式选择、排序算法切换
interface Strategy { void algorithmInterface(); }class Context { private Strategy strategy; public void setStrategy(Strategy s) { strategy = s; } public void contextInterface() { strategy.algorithmInterface(); }}
一对多依赖关系,状态变化自动通知
典型应用:事件监听、订阅发布
interface Observer { void update(String state); }class Subject { private Listobservers = new ArrayList<>(); public void attach(Observer o) { observers.add(o); } public void notifyAllObservers() { for(Observer o : observers) o.update(state); }}
定义算法骨架,子类填充具体步骤
关键方法:钩子方法控制流程
abstract class AbstractClass { final void templateMethod() { primitiveOperation1(); concreteOperation(); primitiveOperation2(); } protected abstract void primitiveOperation1(); protected abstract void primitiveOperation2(); private void concreteOperation() { ... }}
统一遍历不同聚合对象,屏蔽底层差异
Java内置:Collection接口iterator()方法
interface Iterator { boolean hasNext(); Object next();}interface Container { Iterator getIterator();}class NameRepository implements Container { String names[] = {"Robert", "John", "Julie", "Lora"}; public Iterator getIterator() { return new ArrayIterator(); }}
请求沿链传递,首个处理者负责
适用场景:异常处理、审批流程
abstract class Handler { protected Handler successor; public void setSuccessor(Handler s) { successor = s; } public abstract void handleRequest(Request request);}class ConcreteHandlerA extends Handler { public void handleRequest(Request request) { if(canHandle(request)) doHandle(); else successor.handleRequest(request); }}
将请求封装为对象,支持参数化延迟执行
典型应用:撤销重做、事务管理
interface Command { void execute(); }class LightOnCommand implements Command { private Light light; public LightOnCommand(Light light) { this.light = light; } public void execute() { light.on(); }}class RemoteControl { private Command command; public void setCommand(Command cmd) { command = cmd; } public void pressButton() { command.execute(); }}
捕获对象状态快照,支持恢复操作
适用场景:游戏存档、编辑回滚
class Originator { private String state; public Memento createMemento() { return new Memento(state); } public void restoreMemento(Memento m) { state = m.getState(); }}class Memento { private final String state; public Memento(String state) { this.state = state; } public String getState() { return state; }}
行为随状态改变而改变,避免大量条件判断
适用场景:订单状态流转、设备状态机
interface State { void handle(Context context); }class StartState implements State { public void handle(Context context) { context.setState(new RunningState()); }}class Context { private State state; public void request() { state.handle(this); }}
在不修改结构情况下增加操作,双分派机制
典型应用:语法分析、报表生成
interface Visitor { void visit(ElementA element); void visit(ElementB element);}interface Element { void accept(Visitor visitor);}class ConcreteElementA implements Element { public void accept(Visitor v) { v.visit(this); }}class ConcreteVisitor implements Visitor { public void visit(ElementA a) { ... } public void visit(ElementB b) { ... }}
四、实战应用与选型指南
在微服务架构中:
- 工厂模式用于服务发现
- 代理模式实现负载均衡
- 观察者模式处理事件总线
常见误区:
- 过度设计导致模式堆砌
- 模式名称误用(如将单例滥用为全局变量)
- 忽视模式的上下文依赖
五、进阶学习路径
- 阅读《设计模式:可复用面向对象软件的基础》
- 在Kata练习(如重构电话号码格式化)
- 分析Spring源码中的模式应用(IoC容器=工厂+代理)
掌握设计模式不是追求模式数量,而是培养系统思维能力。建议从高频使用的单例、工厂、观察者、策略模式开始实践,逐步建立自己的模式识别库。