Java常用设计模式类图全景解析
设计模式作为软件工程领域的核心知识体系,是Java开发者必须掌握的java常用设计模式类图与实践方法。本页面系统梳理了GoF(Gang of Four)提出的23种经典设计模式,涵盖创建型、结构型与行为型三大类别,以java常用设计模式类图为核心,结合UML类图、核心要素、适用场景、典型代码实现及常见误区,构建完整知识体系。
在现代软件开发中,java常用设计模式类图不仅是架构设计的视觉化表达工具,更是团队沟通与知识沉淀的重要载体。掌握这些模式的结构关系,有助于提升系统可维护性、可扩展性与复用性,尤其在Spring、MyBatis等主流框架源码中广泛存在模式应用实例。
- ⑴ 先理解每种模式的java常用设计模式类图结构(类、接口、关系)
- ⑵ 结合真实项目场景,分析模式的适用边界与权衡点
- ⑶ 动手实现简化版代码,对比不同模式的优劣差异
- ⑷ 对照主流框架源码(如Spring中FactoryBean→工厂模式)加深理解
本页面内容严格遵循UML规范,所有类图均基于标准UML 2.5语法绘制,包含类、接口、抽象类、依赖、关联、聚合、组合、继承等关系,确保技术表达的准确性与专业性。每个模式均附有详细说明与典型示例,满足开发者从理论到实践的完整学习需求。
① 创建型模式(Creational Patterns)
创建型模式关注对象的创建机制,通过抽象化实例化过程,提高系统灵活性与复用性。以下是5种核心创建型模式的java常用设计模式类图解析:
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关键字防止指令重排序。
java常用设计模式类图结构:
- ● Product接口:定义产品规范
- ● ConcreteProduct类:具体产品实现
- ● Creator抽象类:声明工厂方法
- ● ConcreteCreator类:实现工厂方法创建具体产品
- ● 关系:Creator依赖Product;ConcreteCreator继承Creator并实现工厂方法
public interface Product {
void use();
}
public class ConcreteProductA implements Product {
public void use() { }
}
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即采用此模式变体。
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驱动选择。注意:新增产品族时需修改接口,违背开闭原则,适用于产品族稳定场景。
java常用设计模式类图结构:
- ● Product:复杂产品对象
- ● Builder抽象类:定义构建步骤接口
- ● ConcreteBuilder:实现具体构建逻辑
- ● Director:指导构建过程(非必须)
- ● 关系:Builder依赖Product;ConcreteBuilder实现Builder;Director组合Builder
public class Computer {
private String cpu;
private String ram;
private String storage;
}
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均基于此模式。
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常用设计模式类图解析:
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。注意:避免过度使用导致系统混乱。
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均基于此模式。
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代理。注意:静态代理需为每个接口编写代理类,动态代理更灵活。
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的渲染器均基于此模式。
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解析。注意:需处理叶子与容器节点的不一致行为。
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均采用此模式。
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常用设计模式类图解析:
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的分布式锁策略均基于此模式。
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消息订阅。注意:避免循环依赖导致栈溢出。
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过滤器链。注意:链过长可能导致性能问题。
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事务、线程池任务提交均基于此模式。
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,但状态过多时类数量激增。
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() { }
protected boolean authenticate() { }
protected void transmit(String msg) { }
}
java常用设计模式类图优势:提取公共逻辑,子类定制细节。Servlet的doGet/doPost、JDBC的Connection操作均采用此模式。
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。
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。注意:中介者本身可能变得复杂。
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)、游戏存档。注意:备忘录可能占用大量内存,需控制保存频率。
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等工具。