java设计模式及实例
一、创建型模式(5种)
目标:解耦对象的创建与使用。
1. 单例模式(Singleton)
定义:确保一个类只有一个实例,并提供全局访问点。
适用场景:
- 需要全局唯一对象的场景(如配置管理器、线程池、数据库连接池)。
- 需要频繁创建销毁但希望节省资源的场景。
代码示例(双重校验锁):
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;
}
}
2. 工厂方法模式(Factory Method)
定义:定义一个创建对象的接口,由子类决定实例化哪个类。
适用场景:
- 需要将对象创建逻辑封装,客户端不依赖具体类。
- 需要扩展新类型对象时(如日志记录器、数据库连接器)。
代码示例:
interface Product {
void create();
}
class ConcreteProduct implements Product {
@Override
public void create() {
System.out.println("生产具体产品");
}
}
abstract class Factory {
abstract Product createProduct();
}
class ConcreteFactory extends Factory {
@Override
Product createProduct() {
return new ConcreteProduct();
}
}
3. 抽象工厂模式(Abstract Factory)
定义:提供一个创建一系列相关或依赖对象的接口,无需指定具体类。
适用场景:
- 需要创建一组相互关联的产品(如跨平台 UI 组件、不同风格的 GUI)。
- 系统需要独立于产品的创建、组合和表示。
代码示例(跨平台 UI 组件):
interface Button { void render(); }
interface Checkbox { void check(); }
// Windows 风格组件
class WinButton implements Button {
public void render() { System.out.println("Windows 按钮"); }
}
class WinCheckbox implements Checkbox {
public void check() { System.out.println("Windows 复选框"); }
}
// Mac 风格组件
class MacButton implements Button {
public void render() { System.out.println("Mac 按钮"); }
}
class MacCheckbox implements Checkbox {
public void check() { System.out.println("Mac 复选框"); }
}
// 抽象工厂接口
interface GUIFactory {
Button createButton();
Checkbox createCheckbox();
}
class WinFactory implements GUIFactory {
public Button createButton() { return new WinButton(); }
public Checkbox createCheckbox() { return new WinCheckbox(); }
}
class MacFactory implements GUIFactory {
public Button createButton() { return new MacButton(); }
public Checkbox createCheckbox() { return new MacCheckbox(); }
}
4. 建造者模式(Builder)
定义:分步构建复杂对象,分离构建过程与表示。
适用场景:
- 对象构造过程复杂(如包含多个可选参数)。
- 需要生成不同表示的对象(如 HTML 和 PDF 报告)。
代码示例(构建计算机对象):
class Computer {
private String cpu;
private String ram;
// 其他属性...
static class Builder {
private Computer computer = new Computer();
public Builder setCpu(String cpu) {
computer.cpu = cpu;
return this;
}
public Builder setRam(String ram) {
computer.ram = ram;
return this;
}
public Computer build() { return computer; }
}
}
// 使用
Computer computer = new Computer.Builder()
.setCpu("Intel i7")
.setRam("16GB")
.build();
5. 原型模式(Prototype)
定义:通过复制现有对象创建新对象,减少重复初始化开销。
适用场景:
- 对象创建成本较高(如数据库查询结果缓存)。
- 需要动态生成对象副本的场景(如游戏中的角色克隆)。
代码示例:
class Prototype implements Cloneable {
private String data;
public Prototype(String data) { this.data = data; }
@Override
public Prototype clone() {
try {
return (Prototype) super.clone();
} catch (CloneNotSupportedException e) {
throw new AssertionError();
}
}
}
// 使用
Prototype proto1 = new Prototype("原始数据");
Prototype proto2 = proto1.clone();
二、结构型模式(7种)
目标:处理类与对象的组合关系。
6. 适配器模式(Adapter)
定义:使不兼容接口的类协同工作。
适用场景:
- 需要复用现有类,但其接口与系统不兼容(如旧系统升级)。
- 需要统一多个类的接口(如第三方库适配)。
代码示例(对象适配器):
class LegacyPrinter {
void printDocument() { System.out.println("旧式打印"); }
}
interface ModernPrinter {
void print();
}
class PrinterAdapter implements ModernPrinter {
private LegacyPrinter legacyPrinter;
public PrinterAdapter(LegacyPrinter printer) {
this.legacyPrinter = printer;
}
public void print() {
legacyPrinter.printDocument();
}
}
7. 桥接模式(Bridge)
定义:将抽象与实现分离,使两者独立变化。
适用场景:
- 需要在抽象和实现间建立动态绑定(如不同数据库驱动)。
- 需要避免类爆炸(如形状与颜色的组合)。
代码示例(形状与颜色分离):
interface Color { void applyColor(); }
abstract class Shape {
protected Color color;
public Shape(Color color) { this.color = color; }
abstract void draw();
}
class Circle extends Shape {
public Circle(Color color) { super(color); }
void draw() {
System.out.print("圆形:");
color.applyColor();
}
}
class RedColor implements Color {
public void applyColor() { System.out.println("红色"); }
}
8. 组合模式(Composite)
定义:以树形结构处理对象的部分-整体关系。
适用场景:
- 需要表示对象的层次结构(如文件系统、菜单树)。
- 希望客户端统一处理单个对象和组合对象。
代码示例:
interface Component { void operation(); }
class Leaf implements Component {
public void operation() {
System.out.println("叶子节点操作");
}
}
class Composite implements Component {
private List<Component> children = new ArrayList<>();
public void add(Component c) { children.add(c); }
public void operation() {
for (Component c : children) {
c.operation();
}
}
}
9. 装饰器模式(Decorator)
定义:动态地为对象添加职责。
适用场景:
- 需要在不修改代码的情况下扩展对象功能(如 Java IO 流)。
- 需要动态组合多种功能(如咖啡加糖、加牛奶)。
代码示例(咖啡加料):
interface Coffee {
double getCost();
String getDescription();
}
class SimpleCoffee implements Coffee {
public double getCost() { return 10; }
public String getDescription() { return "普通咖啡"; }
}
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 double getCost() { return super.getCost() + 2; }
public String getDescription() {
return super.getDescription() + ", 加牛奶";
}
}
10. 外观模式(Facade)
定义:为复杂子系统提供统一入口。
适用场景:
- 需要简化复杂系统的调用(如启动计算机、电商下单流程)。
- 需要将子系统与客户端解耦。
代码示例(启动计算机):
class CPU { void start() { System.out.println("启动CPU"); } }
class Memory { void load() { System.out.println("加载内存"); } }
class ComputerFacade {
private CPU cpu = new CPU();
private Memory memory = new Memory();
void start() {
cpu.start();
memory.load();
}
}
// 使用
ComputerFacade computer = new ComputerFacade();
computer.start();
11. 享元模式(Flyweight)
定义:共享大量细粒度对象,减少内存消耗。
适用场景:
- 存在大量重复对象(如文本编辑器中的字符对象)。
- 对象的大部分状态可以外部化。
代码示例(共享树类型):
class TreeType {
private String name;
public TreeType(String name) { this.name = name; }
void draw(int x, int y) {
System.out.printf("绘制%s树在(%d,%d)\n", name, x, y);
}
}
class TreeFactory {
private static Map<String, TreeType> pool = new HashMap<>();
public static TreeType getTreeType(String name) {
if (!pool.containsKey(name)) {
pool.put(name, new TreeType(name));
}
return pool.get(name);
}
}
12. 代理模式(Proxy)
定义:控制对对象的访问,增强功能(如延迟加载、权限控制)。
适用场景:
- 需要延迟加载大对象(如图片懒加载)。
- 需要保护敏感对象(如权限控制代理)。
代码示例(图片代理):
interface Image { void display(); }
class RealImage implements Image {
private String filename;
public RealImage(String filename) {
this.filename = filename;
loadFromDisk();
}
private void loadFromDisk() {
System.out.println("加载图片:" + filename);
}
public void display() {
System.out.println("显示图片:" + filename);
}
}
class ProxyImage implements Image {
private RealImage realImage;
private String filename;
public ProxyImage(String filename) { this.filename = filename; }
public void display() {
if (realImage == null) {
realImage = new RealImage(filename);
}
realImage.display();
}
}
三、行为型模式(11种)
目标:处理对象间的交互与职责分配。
13. 责任链模式(Chain of Responsibility)
定义:将请求沿处理链传递,直到有对象处理它。
适用场景:
- 需要动态指定请求处理者(如审批流程、异常处理)。
- 需要解耦请求发送者和接收者。
代码示例(审批流程):
abstract class Handler {
protected Handler next;
public void setNext(Handler next) { this.next = next; }
abstract void handleRequest(int request);
}
class Manager extends Handler {
public void handleRequest(int request) {
if (request < 1000) {
System.out.println("经理审批通过");
} else if (next != null) {
next.handleRequest(request);
}
}
}
class CEO extends Handler {
public void handleRequest(int request) {
if (request >= 1000) {
System.out.println("CEO 审批通过");
}
}
}
14. 命令模式(Command)
定义:将请求封装为对象,支持撤销、队列等操作。
适用场景:
- 需要实现请求的撤销/重做(如文本编辑器)。
- 需要将请求排队或记录日志。
代码示例(遥控器控制灯):
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 command) { this.command = command; }
public void pressButton() { command.execute(); }
}
15. 解释器模式(Interpreter)
定义:定义语言的语法,并用解释器解析句子。
适用场景:
- 需要解析特定语法(如 SQL 解析、数学表达式计算)。
- 语法较简单且效率非关键因素。
代码示例(简单布尔表达式):
interface Expression { boolean interpret(String context); }
class TerminalExpression implements Expression {
private String data;
public TerminalExpression(String data) { this.data = data; }
public boolean interpret(String context) {
return context.contains(data);
}
}
class OrExpression implements Expression {
private Expression expr1, expr2;
public OrExpression(Expression e1, Expression e2) {
this.expr1 = e1; this.expr2 = e2;
}
public boolean interpret(String context) {
return expr1.interpret(context) || expr2.interpret(context);
}
}
16. 迭代器模式(Iterator)
定义:提供顺序访问聚合对象元素的方法。
适用场景:
- 需要统一遍历不同结构的集合(如列表、树、图)。
- 需要隐藏集合的内部实现。
代码示例(自定义集合迭代器):
interface Iterator<T> { boolean hasNext(); T next(); }
class NameRepository implements Iterable<String> {
private String[] names = {"Alice", "Bob"};
public Iterator<String> iterator() {
return new NameIterator();
}
private class NameIterator implements Iterator<String> {
int index = 0;
public boolean hasNext() { return index < names.length; }
public String next() { return names[index++]; }
}
}
17. 中介者模式(Mediator)
定义:通过中介对象封装对象间的交互,降低耦合。
适用场景:
- 对象间交互复杂(如聊天室、飞机调度系统)。
- 需要集中管理对象间的通信。
代码示例(聊天室):
class ChatRoom {
public static void sendMessage(User user, String message) {
System.out.printf("[%s]: %s\n", user.getName(), message);
}
}
class User {
private String name;
public User(String name) { this.name = name; }
public void sendMessage(String message) {
ChatRoom.sendMessage(this, message);
}
public String getName() { return name; }
}
18. 备忘录模式(Memento)
定义:捕获对象状态并保存,以便后续恢复。
适用场景:
- 需要实现撤销/重做功能(如文本编辑器、游戏存档)。
- 需要保存对象历史状态。
代码示例(编辑器撤销):
class Editor {
private String content;
public void setContent(String content) { this.content = content; }
public String getContent() { return content; }
public EditorMemento save() { return new EditorMemento(content); }
public void restore(EditorMemento memento) { content = memento.getContent(); }
}
class EditorMemento {
private final String content;
public EditorMemento(String content) { this.content = content; }
public String getContent() { return content; }
}
19. 观察者模式(Observer)
定义:定义对象间的一对多依赖,状态变化时自动通知。
适用场景:
- 需要实现事件监听(如 GUI 按钮点击、股票价格变动)。
- 一个对象状态变化需要通知其他对象。
代码示例(新闻订阅):
interface Observer { void update(String message); }
class NewsSubscriber implements Observer {
public void update(String message) {
System.out.println("收到新闻:" + message);
}
}
abstract class Subject {
private List<Observer> observers = new ArrayList<>();
public void attach(Observer o) { observers.add(o); }
public void notifyObservers(String message) {
for (Observer o : observers) {
o.update(message);
}
}
}
class NewsPublisher extends Subject {
public void publishNews(String news) {
notifyObservers(news);
}
}
20. 状态模式(State)
定义:允许对象在内部状态改变时改变行为。
适用场景:
- 对象行为依赖于状态且状态转换复杂(如电梯控制、订单状态)。
- 需要消除大量条件分支语句。
代码示例(电梯状态):
interface ElevatorState {
void handle(Elevator elevator);
}
class StoppedState implements ElevatorState {
public void handle(Elevator elevator) {
System.out.println("电梯已停止");
elevator.setState(new RunningState());
}
}
class RunningState implements ElevatorState {
public void handle(Elevator elevator) {
System.out.println("电梯运行中");
elevator.setState(new StoppedState());
}
}
class Elevator {
private ElevatorState state;
public Elevator() { state = new StoppedState(); }
public void setState(ElevatorState state) { this.state = state; }
public void request() { state.handle(this); }
}
21. 策略模式(Strategy)
定义:定义算法族,使其可互换。
适用场景:
- 需要在运行时选择不同算法(如排序策略、支付方式)。
- 需要隔离算法实现与使用代码。
代码示例(支付策略):
interface PaymentStrategy { void pay(int amount); }
class CreditCardPayment implements PaymentStrategy {
public void pay(int amount) {
System.out.println("信用卡支付:" + amount);
}
}
class AlipayPayment implements PaymentStrategy {
public void pay(int amount) {
System.out.println("支付宝支付:" + amount);
}
}
class ShoppingCart {
private PaymentStrategy strategy;
public void setStrategy(PaymentStrategy strategy) {
this.strategy = strategy;
}
public void checkout(int amount) {
strategy.pay(amount);
}
}
22. 模板方法模式(Template Method)
定义:定义算法骨架,允许子类重写特定步骤。
适用场景:
- 需要固定算法流程但允许某些步骤灵活变化(如工作流、数据解析)。
- 需要复用公共代码结构。
代码示例(游戏流程):
abstract class Game {
abstract void initialize();
abstract void startPlay();
abstract void endPlay();
public final void play() { // 模板方法
initialize();
startPlay();
endPlay();
}
}
class Cricket extends Game {
void initialize() { System.out.println("板球初始化"); }
void startPlay() { System.out.println("开始玩板球"); }
void endPlay() { System.out.println("结束板球游戏"); }
}
23. 访问者模式(Visitor)
定义:在不修改类的前提下,为类添加新操作。
适用场景:
- 需要对复杂对象结构执行多种不相关操作(如编译器语法树分析)。
- 需要将数据结构与数据操作分离。
代码示例(计算机部件访问):
interface ComputerPart { void accept(ComputerPartVisitor visitor); }
class Keyboard implements ComputerPart {
public void accept(ComputerPartVisitor visitor) {
visitor.visit(this);
}
}
interface ComputerPartVisitor {
void visit(Keyboard keyboard);
void visit(Mouse mouse);
}
class DisplayVisitor implements ComputerPartVisitor {
public void visit(Keyboard keyboard) {
System.out.println("显示键盘");
}
public void visit(Mouse mouse) {
System.out.println("显示鼠标");
}
}
四、总结
设计模式的核心价值:
- 代码复用:通过模式化方案减少重复代码。
- 解耦与扩展:分离变化与不变部分,提升系统灵活性。
- 可维护性:规范化代码结构,降低维护成本。
注意:
- 理解模式意图,而非死记硬背。
- 结合项目实践,选择合适模式,避免过度设计。
- 阅读开源框架源码(如 Spring、MyBatis),观察模式的应用。

1047

被折叠的 条评论
为什么被折叠?



