Java常用设计模式类图全景解析

设计模式作为软件工程领域的核心知识体系,是Java开发者必须掌握的java常用设计模式类图与实践方法。本页面系统梳理了GoF(Gang of Four)提出的23种经典设计模式,涵盖创建型、结构型与行为型三大类别,以java常用设计模式类图为核心,结合UML类图、核心要素、适用场景、典型代码实现及常见误区,构建完整知识体系。

在现代软件开发中,java常用设计模式类图不仅是架构设计的视觉化表达工具,更是团队沟通与知识沉淀的重要载体。掌握这些模式的结构关系,有助于提升系统可维护性、可扩展性与复用性,尤其在Spring、MyBatis等主流框架源码中广泛存在模式应用实例。

⚡ 学习路径建议
  • ⑴ 先理解每种模式的java常用设计模式类图结构(类、接口、关系)
  • ⑵ 结合真实项目场景,分析模式的适用边界与权衡点
  • ⑶ 动手实现简化版代码,对比不同模式的优劣差异
  • ⑷ 对照主流框架源码(如Spring中FactoryBean→工厂模式)加深理解

本页面内容严格遵循UML规范,所有类图均基于标准UML 2.5语法绘制,包含类、接口、抽象类、依赖、关联、聚合、组合、继承等关系,确保技术表达的准确性与专业性。每个模式均附有详细说明与典型示例,满足开发者从理论到实践的完整学习需求。

① 创建型模式(Creational Patterns)

创建型模式关注对象的创建机制,通过抽象化实例化过程,提高系统灵活性与复用性。以下是5种核心创建型模式的java常用设计模式类图解析:

⚙️ 单例模式(Singleton) 创建型

java常用设计模式类图核心结构:

  • ● 单例类:私有静态实例字段、私有构造器、公共静态获取方法
  • ● 关系:无外部依赖,仅内部维护唯一实例
public class Singleton { private static volatile Singleton instance = null; private Singleton() {} public static synchronized Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; } }

java常用设计模式类图典型应用场景:日志管理器、线程池、配置中心、缓存管理器等需全局唯一对象的场景。注意:双重检查锁(DCL)实现需volatile关键字防止指令重排序。

⚙️ 工厂方法模式(Factory Method) 创建型

java常用设计模式类图结构:

  • ● Product接口:定义产品规范
  • ● ConcreteProduct类:具体产品实现
  • ● Creator抽象类:声明工厂方法
  • ● ConcreteCreator类:实现工厂方法创建具体产品
  • ● 关系:Creator依赖Product;ConcreteCreator继承Creator并实现工厂方法
public interface Product { void use(); } public class ConcreteProductA implements Product { public void use() { // 实现A产品逻辑 } } public abstract class Creator { public abstract Product factoryMethod(); public void operation() { Product p = factoryMethod(); p.use(); } } public class ConcreteCreatorA extends Creator { public Product factoryMethod() { return new ConcreteProductA(); } }

java常用设计模式类图优势:符合开闭原则,新增产品无需修改工厂基类。Spring中BeanFactory即采用此模式变体。

⚙️ 抽象工厂模式(Abstract Factory) 创建型

java常用设计模式类图关键点:

  • ● ProductA/ProductB接口:定义产品族中不同维度的产品
  • ● ConcreteProductA1/B1、ConcreteProductA2/B2:具体产品实现
  • ● AbstractFactory接口:声明多个工厂方法(创建ProductA与ProductB)
  • ● ConcreteFactory1/2:实现创建同一系列产品的工厂方法
  • ● 关系:AbstractFactory依赖多个Product接口;ConcreteFactory继承AbstractFactory
public interface UIFactory { Button createButton(); Checkbox createCheckbox(); } public class WindowsUIFactory implements UIFactory { public Button createButton() { return new WindowsButton(); } public Checkbox createCheckbox() { return new WindowsCheckbox(); } } public class MacUIFactory implements UIFactory { public Button createButton() { return new MacButton(); } public Checkbox createCheckbox() { return new MacCheckbox(); } }

java常用设计模式类图典型应用:Java Swing的UIManager、JDBC驱动选择。注意:新增产品族时需修改接口,违背开闭原则,适用于产品族稳定场景。

⚙️ 建造者模式(Builder) 创建型

java常用设计模式类图结构:

  • ● Product:复杂产品对象
  • ● Builder抽象类:定义构建步骤接口
  • ● ConcreteBuilder:实现具体构建逻辑
  • ● Director:指导构建过程(非必须)
  • ● 关系:Builder依赖Product;ConcreteBuilder实现Builder;Director组合Builder
public class Computer { private String cpu; private String ram; private String storage; // getter/setter... } public abstract class ComputerBuilder { protected Computer computer = new Computer(); public abstract void buildCPU(); public abstract void buildRAM(); public abstract void buildStorage(); public Computer getComputer() { return computer; } } public class GamingComputerBuilder extends ComputerBuilder { public void buildCPU() { computer.setCPU("Intel i9"); } public void buildRAM() { computer.setRAM("32GB"); } public void buildStorage() { computer.setStorage("1TB SSD"); } } public class Director { public Computer construct(ComputerBuilder builder) { builder.buildCPU(); builder.buildRAM(); builder.buildStorage(); return builder.getComputer(); } }

java常用设计模式类图优势:分离构建与表示,支持精细控制构建过程。MyBatis的SqlSessionFactoryBuilder、Lombok的@Builder均基于此模式。

⚙️ 原型模式(Prototype) 创建型

java常用设计模式类图核心:

  • ● Prototype抽象类:声明clone方法
  • ● ConcretePrototype:实现clone方法(浅拷贝/深拷贝)
  • ● 关系:ConcretePrototype继承Prototype并实现clone
public class User implements Cloneable { private String name; private Address address; // 需深拷贝时需手动处理 public User(String name) { this.name = name; } public User clone() { try { return (User) super.clone(); } catch (CloneNotSupportedException e) { throw new RuntimeException(e); } } }

java常用设计模式类图注意:Java中clone()需谨慎处理深浅拷贝问题。Spring中@Scope("prototype")即基于原型模式,每次请求返回新实例。

⚡ 创建型模式对比速览
模式 核心目的 适用场景 优缺点
单例模式 确保唯一实例 资源管理器、日志系统 节省资源;线程安全需额外处理
工厂方法 延迟实例化到子类 产品结构稳定,扩展产品族 符合开闭原则;每类产品需独立工厂
抽象工厂 创建产品族 多系列产品需统一管理 保证产品族一致性;新增产品困难
建造者 分步构建复杂对象 对象构建过程复杂、步骤可变 隔离构建与表示;增加新Builder复杂
原型模式 通过拷贝创建对象 对象创建成本高、结构复杂 性能高;深拷贝实现复杂

② 结构型模式(Structural Patterns)

结构型模式关注类与对象的组合,形成更大结构。以下是7种核心结构型模式的java常用设计模式类图解析:

⚙️ 适配器模式(Adapter) 结构型

java常用设计模式类图两种实现:

  • ● 类适配器:Adapter继承Adaptee并实现Target接口
  • ● 对象适配器:Adapter组合Adaptee并实现Target接口(推荐)
public class Adapter implements Target { private Adaptee adaptee; public Adapter(Adaptee adaptee) { this.adaptee = adaptee; } public void request() { adaptee.specificRequest(); // 转发调用 } }

java常用设计模式类图典型应用:JDK中的InputStreamReader(字符流→字节流适配)、Spring MVC中的HandlerAdapter。注意:避免过度使用导致系统混乱。

⚙️ 装饰器模式(Decorator) 结构型

java常用设计模式类图结构:

  • ● Component接口:定义核心功能
  • ● ConcreteComponent:具体组件
  • ● Decorator抽象类:持有Component引用,实现Component接口
  • ● ConcreteDecorator:增强功能的具体装饰器
  • ● 关系:Decorator组合Component;ConcreteDecorator继承Decorator
public interface Coffee { String getDescription(); double getCost(); } public class SimpleCoffee implements Coffee { public String getDescription() { return "Simple Coffee"; } public double getCost() { return 5.0; } } public abstract class CoffeeDecorator implements Coffee { protected Coffee coffee; public CoffeeDecorator(Coffee coffee) { this.coffee = coffee; } } public class MilkDecorator extends CoffeeDecorator { public MilkDecorator(Coffee coffee) { super(coffee); } public String getDescription() { return coffee.getDescription() + ", Milk"; } public double getCost() { return coffee.getCost() + 1.5; } }

java常用设计模式类图优势:动态扩展功能,避免子类膨胀。Java IO流(BufferedInputStream)、Spring的@Cacheable均基于此模式。

⚙️ 代理模式(Proxy) 结构型

java常用设计模式类图类型:

  • ● 静态代理:代理类手动编写
  • ● 动态代理:JDK动态代理(InvocationHandler)、CGLIB(继承)
  • ● 关系:Proxy与RealSubject实现同一接口;Proxy组合RealSubject
public class ProxyService implements Service { private Service target; public ProxyService(Service target) { this.target = target; } public void execute() { System.out.println("Before execution"); target.execute(); // 真实调用 System.out.println("After execution"); } }

java常用设计模式类图典型应用:Spring AOP、Retrofit接口代理、MyBatis Mapper代理。注意:静态代理需为每个接口编写代理类,动态代理更灵活。

⚙️ 桥接模式(Bridge) 结构型

java常用设计模式类图结构:

  • ● Abstraction:定义抽象部分,持有Implementor引用
  • ● RefinedAbstraction:扩展抽象
  • ● Implementor接口:定义实现部分接口
  • ● ConcreteImplementor:具体实现
  • ● 关系:Abstraction组合Implementor(组合关系)
public interface DrawAPI { void drawCircle(int radius, int x, int y); } public class RedCircle implements DrawAPI { public void drawCircle(int r, int x, int y) { System.out.println("Drawing Circle[red, radius=" + r + "]"); } } public abstract class Shape { protected DrawAPI drawAPI; protected Shape(DrawAPI drawAPI) { this.drawAPI = drawAPI; } public abstract void draw(); } public class Circle extends Shape { private int x, y, radius; public Circle(int x, int y, int r, DrawAPI drawAPI) { super(drawAPI); this.x = x; this.y = y; this.radius = r; } public void draw() { drawAPI.drawCircle(radius, x, y); } }

java常用设计模式类图优势:分离抽象与实现,支持独立扩展。JDBC驱动、Swing的渲染器均基于此模式。

⚙️ 组合模式(Composite) 结构型

java常用设计模式类图结构:

  • ● Component接口:声明子类公共接口
  • ● Leaf:叶子节点(无子节点)
  • ● Composite:容器节点(包含子组件)
  • ● 关系:Composite组合Component列表;Leaf与Composite继承Component
public abstract class Component { protected String name; public Component(String name) { this.name = name; } public abstract void add(Component c); public abstract void remove(Component c); public abstract void display(int depth); } public class Leaf extends Component { public Leaf(String name) { super(name); } public void add(Component c) { // 不支持 } public void remove(Component c) {} public void display(int depth) { System.out.println("-".repeat(depth) + name); } } public class Composite extends Component { private List<Component> children = new ArrayList<>(); public Composite(String name) { super(name); } public void add(Component c) { children.add(c); } public void remove(Component c) { children.remove(c); } public void display(int depth) { System.out.println("-".repeat(depth) + name); children.forEach(c → c.display(depth + 2)); } }

java常用设计模式类图典型应用:文件系统、GUI组件树(JFrame→JPanel→JButton)、XML解析。注意:需处理叶子与容器节点的不一致行为。

⚙️ 外观模式(Facade) 结构型

java常用设计模式类图结构:

  • ● Facade类:提供统一高层接口
  • ● Subsystem classes:子系统类(子模块)
  • ● 关系:Facade组合多个子系统类
public class CPU { public void freeze() {} public void jump(long pos) {} } public class Memory { public void load(long pos, byte[] data) {} } public class HardDrive { public byte[] read(long lba, int size) { return new byte[0]; } } public class ComputerFacade { private CPU cpu = new CPU(); private Memory memory = new Memory(); private HardDrive hd = new HardDrive(); public void start() { cpu.freeze(); memory.load(0, hd.read(0, 512)); cpu.jump(0); cpu.execute(); } }

java常用设计模式类图优势:简化复杂子系统调用。Hibernate的SessionFactory、REST Client SDK均采用此模式。

⚙️ 享元模式(Flyweight) 结构型

java常用设计模式类图核心:

  • ● Flyweight接口:共享对象接口
  • ● ConcreteFlyweight:具体共享对象(内部状态)
  • ● FlyweightFactory:享元工厂,管理对象池
  • ● 关系:Factory返回共享对象;内部状态存储于Flyweight中
public class Character implements Flyweight { private final char symbol; // 内部状态 public Character(char s) { symbol = s; } public void display(int size) { // 外部状态 } } public class FlyweightFactory { private Map<Character, Flyweight> pool = new HashMap<>(); public Flyweight getCharacter(char key) { pool.computeIfAbsent(key, k → new Character(k)); return pool.get(key); } }

java常用设计模式类图应用:String常量池、Integer.valueOf()缓存、线程池。注意:仅适用于大量细粒度对象且内部状态可共享的场景。

③ 行为型模式(Behavioral Patterns)

行为型模式关注对象间的职责分配与通信。以下是11种核心行为型模式的java常用设计模式类图解析:

⚙️ 策略模式(Strategy) 行为型

java常用设计模式类图结构:

  • ● Strategy接口:定义算法族公共接口
  • ● ConcreteStrategy:具体算法实现
  • ● Context:持有Strategy引用,封装上下文
  • ● 关系:Context组合Strategy;ConcreteStrategy实现Strategy
public interface Strategy { int doAlgorithm(int a, int b); } public class AddStrategy implements Strategy { public int doAlgorithm(int a, int b) { return a + b; } } public class MultiplyStrategy implements Strategy { public int doAlgorithm(int a, int b) { return a * b; } } public class Context { private Strategy strategy; public Context(Strategy s) { this.strategy = s; } public void executeStrategy(int a, int b) { System.out.println(strategy.doAlgorithm(a, b)); } }

java常用设计模式类图优势:消除if-else分支,支持运行时切换算法。Java Collections.sort()的Comparator、Redisson的分布式锁策略均基于此模式。

⚙️ 观察者模式(Observer) 行为型

java常用设计模式类图结构:

  • ● Subject:维护观察者列表,提供注册/通知方法
  • ● Observer接口:定义更新方法
  • ● ConcreteSubject/Observer:具体实现
  • ● 关系:Subject组合Observer列表;Observer依赖Subject
public interface Observer { void update(String message); } public class ConcreteObserver implements Observer { private String name; public ConcreteObserver(String n) { name = n; } public void update(String msg) { System.out.println(name + " received: " + msg); } } public class ConcreteSubject { private List<Observer> observers = new ArrayList<>(); public void attach(Observer o) { observers.add(o); } public void notifyObservers(String msg) { observers.forEach(o → o.update(msg)); } }

java常用设计模式类图应用:Java EventListener、Spring ApplicationEvent、MQ消息订阅。注意:避免循环依赖导致栈溢出。

⚙️ 责任链模式(Chain of Responsibility) 行为型

java常用设计模式类图结构:

  • ● Handler抽象类:定义处理方法与后继链
  • ● ConcreteHandler:具体处理者
  • ● 关系:Handler持有next Handler引用
public abstract class Logger { public static int INFO = 1; public static int DEBUG = 2; public static int ERROR = 3; protected int level; protected Logger next; public Logger(int lvl) { level = lvl; } public void setNext(Logger l) { next = l; } public void message(String msg, int priority) { if (priority <= level) { write(msg); } if (next != null) { next.message(msg, priority); } } protected abstract void write(String msg); } public class ConsoleLogger extends Logger { public ConsoleLogger(int level) { super(level); } protected void write(String msg) { System.out.println("CONSOLE: " + msg); } }

java常用设计模式类图典型应用:Servlet Filter链、Dubbo Filter、Spring Security过滤器链。注意:链过长可能导致性能问题。

⚙️ 命令模式(Command) 行为型

java常用设计模式类图结构:

  • ● Command接口:声明execute()方法
  • ● ConcreteCommand:具体命令,持有Receiver引用
  • ● Receiver:真正执行者
  • ● Invoker:调用命令
  • ● 关系:Command依赖Receiver;Invoker组合Command
public interface Command { void execute(); } public class LightOnCommand implements Command { private Light light; public LightOnCommand(Light l) { light = l; } public void execute() { light.on(); } } public class RemoteControl { private Command command; public void setCommand(Command c) { command = c; } public void pressButton() { command.execute(); } }

java常用设计模式类图优势:将请求封装为对象,支持排队、记录日志、撤销操作。GUI事件处理(Action)、Redis事务、线程池任务提交均基于此模式。

⚙️ 状态模式(State) 行为型

java常用设计模式类图结构:

  • ● Context:持有State引用
  • ● State接口:定义状态相关方法
  • ● ConcreteState:具体状态实现
  • ● 关系:Context组合State;ConcreteState可改变Context的State
public interface State { void insertCoin(); void ejectCoin(); void turnCrank(); void dispense(); } public class HasCoinState implements State { private GumballMachine machine; public HasCoinState(GumballMachine m) { machine = m; } public void insertCoin() { System.out.println("Already has coin"); } public void ejectCoin() { System.out.println("Coin returned"); machine.setState(machine.getNoCoinState()); } public void turnCrank() { System.out.println("Crank turned..."); machine.setState(machine.getSoldState()); } public void dispense() {} } public class GumballMachine { private State state; public void setState(State s) { this.state = s; } }

java常用设计模式类图应用:订单状态机、网络连接状态、有限状态机(FSM)。避免大量if-else,但状态过多时类数量激增。

⚙️ 模板方法模式(Template Method) 行为型

java常用设计模式类图核心:

  • ● AbstractClass:定义模板方法(final),声明抽象/钩子方法
  • ● ConcreteClass:实现具体步骤
  • ● 关系:ConcreteClass继承AbstractClass
public abstract class AbstractNetwork { public final void post(String message) { connect(); if (authenticate()) { transmit(message); disconnect(); } } protected abstract void connect(); protected abstract boolean authenticate(); protected abstract void transmit(String msg); protected void disconnect() {} // 钩子方法 } public class FacebookNetwork extends AbstractNetwork { protected void connect() { // Facebook连接逻辑 } protected boolean authenticate() { // Facebook认证 } protected void transmit(String msg) { // Facebook发送 } }

java常用设计模式类图优势:提取公共逻辑,子类定制细节。Servlet的doGet/doPost、JDBC的Connection操作均采用此模式。

⚙️ 访问者模式(Visitor) 行为型

java常用设计模式类图结构:

  • ● Visitor接口:定义visit方法(重载)
  • ● Element接口:接受访问者(accept)
  • ● ConcreteVisitor/Element:具体实现
  • ● 关系:Element.accept(visitor) → visitor.visit(this)
public interface Element { void accept(Visitor v); } public class ConcreteElementA implements Element { public void accept(Visitor v) { v.visit(this); } public String operationA() { return "A"; } } public interface Visitor { void visit(ConcreteElementA a); void visit(ConcreteElementB b); } public class ConcreteVisitor implements Visitor { public void visit(ConcreteElementA a) { System.out.println("Visiting A: " + a.operationA()); } }

java常用设计模式类图优势:在不修改元素类前提下增加新操作。AST语法树处理、Maven插件扩展基于此模式。注意:元素类变化时需修改所有Visitor。

⚙️ 中介者模式(Mediator) 行为型

java常用设计模式类图结构:

  • ● Mediator接口:定义同事间通信方法
  • ● ConcreteMediator:具体中介者,管理同事对象
  • ● Colleague:同事类,持有Mediator引用
  • ● 关系:Colleague依赖Mediator;Mediator组合Colleague列表
public abstract class Colleague { protected Mediator mediator; public Colleague(Mediator m) { this.mediator = m; } } public class ConcreteColleagueA extends Colleague { public ConcreteColleagueA(Mediator m) { super(m); } public void send(String msg) { mediator.send(msg, this); } public void notify(String msg) { System.out.println("A received: " + msg); } } public class ConcreteMediator implements Mediator { private ConcreteColleagueA colA; private ConcreteColleagueB colB; public void setColleagues(ConcreteColleagueA a, ConcreteColleagueB b) { colA = a; colB = b; } public void send(String msg, Colleague sender) { if (sender == colA) colB.notify(msg); else colA.notify(msg); } }

java常用设计模式类图应用:聊天室、MVC中的Controller、Redisson的RedissonMapMultiMap。注意:中介者本身可能变得复杂。

⚙️ 备忘录模式(Memento) 行为型

java常用设计模式类图结构:

  • ● Originator:原发器,创建/恢复备忘录
  • ● Memento:存储内部状态
  • ● Caretaker:负责保存备忘录
  • ● 关系:Originator创建Memento;Caretaker存储Memento
public class Memento { private String state; public Memento(String s) { this.state = s; } public String getState() { return state; } } public class Originator { private String state; public void setState(String s) { this.state = s; } public Memento saveToMemento() { return new Memento(state); } public void restoreFromMemento(Memento m) { state = m.getState(); } } public class Caretaker { private List<Memento> history = new ArrayList<>(); public void addMemento(Memento m) { history.add(m); } public Memento getMemento(int index) { return history.get(index); } }

java常用设计模式类图应用:数据库事务回滚、编辑器撤销操作(Ctrl+Z)、游戏存档。注意:备忘录可能占用大量内存,需控制保存频率。

⚙️ 解释器模式(Interpreter) 行为型

java常用设计模式类图结构:

  • ● AbstractExpression:抽象表达式
  • ● TerminalExpression:终结符表达式
  • ● NonterminalExpression:非终结符表达式
  • ● Context:共享数据
  • ● 关系:表达式树由Nonterminal组合Terminal
public interface Expression { boolean interpret(String context); } public class TerminalExpression implements Expression { private String data; public TerminalExpression(String d) { data = d; } public boolean interpret(String context) { return context.contains(data); } } public class AndExpression implements Expression { private Expression expr1, expr2; public AndExpression(Expression e1, Expression e2) { expr1 = e1; expr2 = e2; } public boolean interpret(String context) { return expr1.interpret(context) && expr2.interpret(context); } }

java常用设计模式类图应用:正则表达式引擎、SpEL表达式、SQL解析器。注意:仅适用于简单语法,复杂语法应使用ANTLR等工具。

④ Java常用设计模式类图速查表

以下为23种java常用设计模式类图的完整汇总,便于快速检索与对比:

类别 模式名称 核心UML关系 Java典型应用 使用频率
创建型 单例模式 类→类(私有实例) Runtime.getRuntime() ★★★★★
工厂方法 接口←类(继承+组合) Spring BeanFactory ★★★★☆
抽象工厂 接口←类(多工厂方法) JDBC Connection ★★★☆☆
建造者 接口←类(分步构建) StringBuilder ★★★★☆
原型模式 接口←类(clone) Object.clone() ★★★☆☆
结构型 适配器 接口←类(继承/组合) InputStreamReader ★★★★☆
装饰器 接口←类(组合) BufferedInputStream ★★★★★
代理 接口←类(组合) JDK Proxy ★★★★★
桥接 接口←接口(组合) JDBC Driver ★★☆☆☆
组合 接口←类(树形组合) Swing Container ★★★☆☆
外观 类→类(组合) SessionFactory ★★★☆☆
享元 工厂→对象池 String常量池 ★★☆☆☆
行为型 策略 接口←类(组合) Comparator ★★★★★
观察者 接口←类(组合) EventListener ★★★★☆
责任链 类→类(链式组合) FilterChain ★★★☆☆
命令 接口←类(组合) Runnable ★★★★☆
状态 接口←类(组合) StateMachine ★★★☆☆
模板方法 接口←类(继承) Servlet ★★★★☆
访问者 接口←接口(双分派) ASTVisitor ★★☆☆☆
中介者 类→类(组合) ChatRoom ★★☆☆☆
备忘录 类→类(存储) UndoManager ★★☆☆☆
解释器 接口←类(递归组合) SpEL ★☆☆☆☆

⑤ 模式对比与选择指南

⚡ 高频模式深度对比
工厂 vs 抽象工厂
代理 vs 装饰器
策略 vs 状态

工厂方法 vs 抽象工厂

java常用设计模式类图核心差异:

  • ● 工厂方法:一个工厂创建一种产品(Product接口)
  • ● 抽象工厂:一个工厂创建多个产品(ProductA/ ProductB接口)
  • ● 适用场景:
  •  - 工厂方法:产品结构稳定,仅需扩展新产品(新增ConcreteProduct)
  •  - 抽象工厂:产品族稳定(如UI组件:Button+Checkbox),需保证产品一致性

选择建议

  • 若只需扩展产品类型 → 用工厂方法
  • 若需保证产品族一致性 → 用抽象工厂
  • 若产品族频繁变化 → 考虑桥接模式

代理 vs 装饰器

java常用设计模式类图关键区别:

  • ● 目的:
  •  - 代理:控制对对象的访问(安全、延迟加载、远程调用)
  •  - 装饰器:动态添加新功能(增强行为)
  • ● 代理模式中代理与真实对象通常同类型;装饰器中装饰器与原对象类型不同
  • ● 代理模式强调“替代”;装饰器强调“增强”

典型场景

  • 代理:Retrofit接口代理、Spring AOP
  • 装饰器:Java IO流(BufferedInputStream)

策略 vs 状态

java常用设计模式类图对比:

  • ● 共同点:都通过组合替换继承,消除if-else
  • ● 差异:
  •  - 策略:客户端决定使用哪种算法(外部切换)
  •  - 状态:对象自身状态改变导致行为变化(内部切换)
  • ● 状态模式中状态对象可主动改变Context的State;策略模式中客户端控制Strategy

选择建议

  • 算法选择由外部决定 → 策略模式
  • 对象行为随内部状态变化 → 状态模式
  • 混合场景:状态模式可看作“自适应策略”

⑥ 网友最关心的5大热点问题

1. 为什么Spring中单例Bean是线程安全的?

Spring单例Bean的线程安全性取决于:java常用设计模式类图中单例模式的实现方式。Spring默认单例Bean为“无状态”(Stateless),即不保存实例变量,所有数据通过方法参数传递。例如Service层通常无状态,而Controller通过@RequestParam传递数据,因此线程安全。若需保存状态,应使用@Scope("prototype")或同步机制。

2. 适配器与装饰器模式在Spring中如何区分使用?

Spring中:

  • ● 适配器:HandlerAdapter(将不同Handler适配为统一接口)
  • ● 装饰器:RequestContextFilter(增强request对象)
  • ● 关键区别:适配器改变接口;装饰器增强行为但接口不变

3. 观察者模式在Spring事件机制中的实现原理?

Spring事件机制基于观察者模式:java常用设计模式类图中ApplicationEventPublisher(Subject)持有ApplicationListener列表(Observer)。发布事件时,通过SimpleApplicationEventMulticaster同步/异步通知所有监听器。注意:默认同步执行,需异步时配置TaskExecutor。

4. 模板方法与策略模式在MyBatis中的应用?

MyBatis中:

  • ● 模板方法:BaseExecutor.execute()定义流程,子类实现doUpdate/doQuery
  • ● 策略模式:StatementHandler使用ParameterHandler/ResultSetHandler策略
  • ● 关键差异:模板方法由父类控制流程;策略模式由客户端选择策略

5. 如何避免过度设计设计模式?

java常用设计模式类图使用原则:

  • ● 仅在需求明确、模式价值显著时使用
  • ● 避免为用而用:如简单if-else无需策略模式
  • ● 优先考虑KISS原则:简单可维护优先
  • ● 重构时引入:已有代码重构比新写更合理
  • ● 团队共识:确保成员理解模式意图
java设计模式 设计模式类图 UML类图 23种设计模式 创建型模式 结构型模式 行为型模式 Spring源码 工厂模式 单例模式 观察者模式 策略模式 装饰器模式 代理模式