当前位置: 首页 > article >正文

一篇文章巩固技术-----设计模式

设计模式以及Spring结合了哪些模式

一、创建型模式(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;
    }
}

Spring应用:Bean默认作用域就是单例模式,通过IoC容器管理对象生命周期,保证线程安全的同时减少资源消耗

2. 工厂方法(Factory Method)

意图:定义创建对象的接口,让子类决定实例化哪个类
案例:

interface PaymentFactory {
    Payment create();
}

class AlipayFactory implements PaymentFactory {
    public Payment create() {
        return new Alipay();
    }
}

Spring应用:BeanFactory是典型的工厂模式实现,通过ApplicationContext获取Bean时实际使用的是工厂方法

3. 抽象工厂(Abstract Factory)

意图:创建相关或依赖对象的家族
案例:

interface GUIFactory {
    Button createButton();
    Menu createMenu();
}

class WinFactory implements GUIFactory {
    public Button createButton() { return new WinButton(); }
    public Menu createMenu() { return new WinMenu(); }
}

Spring应用:BeanDefinitionRegistryPostProcessor通过抽象工厂模式创建不同环境下的Bean定义

4. 建造者模式(Builder)

意图:分步骤创建复杂对象
案例:

User user = new User.Builder()
                .name("John")
                .age(30)
                .address("NY")
                .build();

Spring应用:RestTemplateBuilder用于构建复杂配置的RestTemplate对象

5. 原型模式(Prototype)

意图:通过复制现有对象来创建新对象
案例:

class Shape implements Cloneable {
    @Override
    public Shape clone() {
        try {
            return (Shape) super.clone();
        } catch (CloneNotSupportedException e) {
            return null;
        }
    }
}

Spring应用:Bean的作用域设置为prototype时,每次获取都会创建新对象

二、结构型模式(7种)

6. 适配器模式(Adapter)

意图:转换接口使得不兼容的类可以协作
代码案例:

// 旧系统接口
interface LegacyPayment {
    void pay(int amount);
}

// 新系统接口
interface ModernPayment {
    void processPayment(double amount);
}

class PaymentAdapter implements ModernPayment {
    private LegacyPayment legacyPayment;
    
    public PaymentAdapter(LegacyPayment legacyPayment) {
        this.legacyPayment = legacyPayment;
    }
    
    public void processPayment(double amount) {
        legacyPayment.pay((int) (amount * 100)); // 转换金额单位
    }
}

Spring应用:HandlerAdapter适配不同Controller类型
目的:兼容旧系统,减少重构成本

7. 装饰器模式(Decorator)

意图:动态添加职责
代码案例:

interface DataSource {
    void writeData(String data);
    String readData();
}

class FileDataSource implements DataSource { /* 基础实现 */ }

class EncryptionDecorator implements DataSource {
    private DataSource wrappee;
    
    public EncryptionDecorator(DataSource source) {
        this.wrappee = source;
    }
    
    public void writeData(String data) {
        wrappee.writeData(encrypt(data));
    }
    
    private String encrypt(String data) { /* 加密逻辑 */ }
}

Spring应用:HttpRequestWrapper增强请求处理能力
目的:动态扩展功能,避免类爆炸

8. 代理模式(Proxy)

意图:控制对象访问
代码案例:

interface Image {
    void display();
}

class RealImage implements Image { /* 加载大文件 */ }

class ImageProxy implements Image {
    private RealImage realImage;
    private String filename;
    
    public ImageProxy(String filename) {
        this.filename = filename;
    }
    
    public void display() {
        if (realImage == null) {
            realImage = new RealImage(filename); // 延迟加载
        }
        realImage.display();
    }
}

Spring应用:AOP的动态代理(@Transactional等)
目的:实现延迟加载、访问控制等非核心功能

9. 外观模式(Facade)

意图:提供统一的高层接口
代码案例:

class OrderProcessingFacade {
    private InventoryService inventory;
    private PaymentService payment;
    private ShippingService shipping;
    
    public void placeOrder(Order order) {
        inventory.checkStock(order);
        payment.processPayment(order);
        shipping.scheduleDelivery(order);
    }
}

Spring应用:JdbcTemplate封装JDBC操作
目的:简化复杂子系统使用

10. 桥接模式(Bridge)

意图:分离抽象与实现
代码案例:

interface Renderer {
    void renderCircle(float radius);
}

class VectorRenderer implements Renderer { /* 矢量渲染 */ }
class RasterRenderer implements Renderer { /* 栅格渲染 */ }

abstract class Shape {
    protected Renderer renderer;
    
    protected Shape(Renderer renderer) {
        this.renderer = renderer;
    }
    
    public abstract void draw();
}

class Circle extends Shape {
    private float radius;
    
    public Circle(float radius, Renderer renderer) {
        super(renderer);
        this.radius = radius;
    }
    
    public void draw() {
        renderer.renderCircle(radius);
    }
}

Spring应用:DataSource与不同驱动实现解耦
目的:独立变化维度,提高扩展性

11. 组合模式(Composite)

意图:将对象组合成树形结构
代码案例:

interface Component {
    void operation();
}

class Leaf implements Component {
    public void operation() { /* 叶子节点操作 */ }
}

class Composite implements Component {
    private List<Component> children = new ArrayList<>();
    
    public void add(Component component) {
        children.add(component);
    }
    
    public void operation() {
        for (Component child : children) {
            child.operation();
        }
    }
}

Spring应用:BeanDefinition的层次结构管理
目的:统一处理整体与部分的关系

12. 享元模式(Flyweight)

意图:高效共享细粒度对象
代码案例:

class TreeType {
    private String name;
    private String color;
    // 共享的固有属性
    
    public TreeType(String name, String color) { /* 初始化 */ }
}

class TreeFactory {
    static Map<String, TreeType> treeTypes = new HashMap<>();
    
    public static TreeType getTreeType(String name, String color) {
        String key = name + "_" + color;
        if (!treeTypes.containsKey(key)) {
            treeTypes.put(key, new TreeType(name, color));
        }
        return treeTypes.get(key);
    }
}

Spring应用:Bean的元数据缓存
目的:减少内存占用,提高性能

三、行为型模式(11种)

13. 观察者模式(Observer Pattern)

意图:定义对象间的一对多依赖关系,当一个对象状态改变时,所有依赖它的对象都会自动收到通知
适用场景:事件驱动系统、消息通知、状态监控等需要解耦的场景

完整代码案例(订单状态通知系统)

import java.util.ArrayList;
import java.util.List;

// 1. 主题接口(被观察者)
interface OrderSubject {
    void registerObserver(OrderObserver observer);
    void removeObserver(OrderObserver observer);
    void notifyObservers();
}

// 2. 具体主题实现
class Order implements OrderSubject {
    private String orderId;
    private String status;
    private List<OrderObserver> observers = new ArrayList<>();

    public Order(String orderId) {
        this.orderId = orderId;
        this.status = "CREATED";
    }

    public void updateStatus(String newStatus) {
        this.status = newStatus;
        notifyObservers(); // 状态变化时通知观察者
    }

    @Override
    public void registerObserver(OrderObserver observer) {
        observers.add(observer);
    }

    @Override
    public void removeObserver(OrderObserver observer) {
        observers.remove(observer);
    }

    @Override
    public void notifyObservers() {
        for (OrderObserver observer : observers) {
            observer.update(this.orderId, this.status);
        }
    }
}

// 3. 观察者接口
interface OrderObserver {
    void update(String orderId, String status);
}

// 4. 具体观察者实现
class EmailNotificationService implements OrderObserver {
    @Override
    public void update(String orderId, String status) {
        System.out.printf("[Email] 订单 %s 状态更新为:%s%n", orderId, status);
        // 实际发送邮件的业务逻辑
    }
}

class SMSNotificationService implements OrderObserver {
    @Override
    public void update(String orderId, String status) {
        System.out.printf("[SMS] 订单 %s 状态更新为:%s%n", orderId, status);
        // 实际发送短信的逻辑
    }
}

// 5. 使用示例
public class ObserverDemo {
    public static void main(String[] args) {
        // 创建订单(被观察者)
        Order order = new Order("ORDER_1001");
        
        // 创建观察者
        OrderObserver emailService = new EmailNotificationService();
        OrderObserver smsService = new SMSNotificationService();
        
        // 注册观察者
        order.registerObserver(emailService);
        order.registerObserver(smsService);
        
        // 模拟状态变化
        order.updateStatus("PAID");
        order.updateStatus("SHIPPED");
        
        // 移除短信通知
        order.removeObserver(smsService);
        order.updateStatus("DELIVERED");
    }
}

/* 输出结果:
[Email] 订单 ORDER_1001 状态更新为:PAID
[SMS] 订单 ORDER_1001 状态更新为:PAID
[Email] 订单 ORDER_1001 状态更新为:SHIPPED
[SMS] 订单 ORDER_1001 状态更新为:SHIPPED
[Email] 订单 ORDER_1001 状态更新为:DELIVERED
*/

模式解析

  1. 核心组件:

    Subject:维护观察者列表,提供注册/注销方法,通知机制

    Observer:定义更新接口,接收状态变更通知

    ConcreteSubject:具体被观察对象,状态变化时触发通知

    ConcreteObserver:实现具体响应逻辑

  2. 实现要点:

    使用接口实现松耦合

    支持动态添加/移除观察者

    避免观察者处理耗时操作(可结合线程池)

  3. 设计优势:

    解耦生产者(被观察者)与消费者(观察者)

    符合开闭原则(新增观察者无需修改被观察者)

    支持广播通信

Spring框架应用
应用场景:事件发布/监听机制
实现方式:

// 1. 自定义事件
public class OrderStatusEvent extends ApplicationEvent {
    private String orderId;
    private String status;

    public OrderStatusEvent(Object source, String orderId, String status) {
        super(source);
        this.orderId = orderId;
        this.status = status;
    }
    // getters...
}

// 2. 事件发布者
@Service
class OrderService {
    @Autowired
    private ApplicationEventPublisher eventPublisher;

    public void updateOrderStatus(String orderId, String newStatus) {
        // 业务逻辑...
        eventPublisher.publishEvent(new OrderStatusEvent(this, orderId, newStatus));
    }
}

// 3. 事件监听器
@Component
class EmailNotificationListener {
    @EventListener
    public void handleOrderEvent(OrderStatusEvent event) {
        System.out.printf("[Spring Event] 订单 %s 状态变更为 %s%n", 
                          event.getOrderId(), event.getStatus());
        // 发送邮件逻辑
    }
}

Spring实现特点:

	使用ApplicationEventPublisher发布事件
	
	通过@EventListener注解实现监听
	
	支持异步处理(配合@Async)
	
	支持事件过滤(使用condition属性)

设计目的:

	实现业务逻辑解耦
	
	支持可插拔的事件处理
	
	简化事件驱动架构实现

14. 策略模式(Strategy Pattern)

意图:定义算法族,封装每个算法,使它们可以互相替换
适用场景:支付方式选择、排序算法切换等需要动态选择行为的场景

// 策略接口
interface PaymentStrategy {
    void pay(int amount);
}

// 具体策略
class AlipayStrategy implements PaymentStrategy {
    public void pay(int amount) {
        System.out.println("支付宝支付:" + amount + "元");
    }
}

class WechatPayStrategy implements PaymentStrategy {
    public void pay(int amount) {
        System.out.println("微信支付:" + amount + "元");
    }
}

// 上下文类
class PaymentContext {
    private PaymentStrategy strategy;
    
    public void setStrategy(PaymentStrategy strategy) {
        this.strategy = strategy;
    }
    
    public void executePayment(int amount) {
        strategy.pay(amount);
    }
}

// 使用
PaymentContext context = new PaymentContext();
context.setStrategy(new AlipayStrategy());
context.executePayment(100);

Spring应用:ResourceLoader 接口的不同实现(ClassPathResource、FileSystemResource)
目的:解耦算法实现与使用,支持运行时切换策略

15. 模板方法模式(Template Method Pattern)

意图:定义算法骨架,允许子类重写特定步骤
适用场景:数据库操作模板、工作流处理

abstract class ReportGenerator {
    // 模板方法(final防止重写)
    public final void generateReport() {
        collectData();
        analyzeData();
        formatReport();
    }
    
    protected abstract void collectData();
    protected abstract void analyzeData();
    
    private void formatReport() {
        System.out.println("生成标准格式报告");
    }
}

class SalesReport extends ReportGenerator {
    protected void collectData() {
        System.out.println("收集销售数据");
    }
    
    protected void analyzeData() {
        System.out.println("分析销售趋势");
    }
}

// 使用
ReportGenerator report = new SalesReport();
report.generateReport();

Spring应用:JdbcTemplate 的 execute() 方法
目的:复用通用流程,规范开发模式

16. 责任链模式(Chain of Responsibility Pattern)

意图:将请求的发送者和接收者解耦,使多个对象都有机会处理请求
适用场景:审批流程、过滤器链

abstract class Handler {
    protected Handler next;
    
    public Handler setNext(Handler next) {
        this.next = next;
        return next;
    }
    
    public abstract void handleRequest(int level);
}

class Manager extends Handler {
    public void handleRequest(int level) {
        if (level <= 2) {
            System.out.println("经理审批通过");
        } else if (next != null) {
            next.handleRequest(level);
        }
    }
}

class Director extends Handler {
    public void handleRequest(int level) {
        if (level <= 5) {
            System.out.println("总监审批通过");
        } else if (next != null) {
            next.handleRequest(level);
        }
    }
}

// 使用
Handler chain = new Manager();
chain.setNext(new Director());

chain.handleRequest(3); // 总监处理
chain.handleRequest(1); // 经理处理

Spring应用:FilterChain 处理HTTP请求
目的:动态组合处理流程,增强扩展性

17. 命令模式(Command Pattern)

意图:将请求封装为对象,支持请求的排队、日志、撤销等操作
适用场景:GUI操作、事务管理

interface Command {
    void execute();
    void undo();
}

class Light {
    void on() { System.out.println("开灯"); }
    void off() { System.out.println("关灯"); }
}

class LightOnCommand implements Command {
    private Light light;
    
    public LightOnCommand(Light light) {
        this.light = light;
    }
    
    public void execute() { light.on(); }
    public void undo() { light.off(); }
}

// 调用者
class RemoteControl {
    private Command command;
    
    public void setCommand(Command command) {
        this.command = command;
    }
    
    public void pressButton() {
        command.execute();
    }
}

// 使用
Light light = new Light();
RemoteControl remote = new RemoteControl();
remote.setCommand(new LightOnCommand(light));
remote.pressButton();

Spring应用:JdbcTemplate 的事务命令封装
目的:解耦请求发起者与执行者,支持复杂操作管理

18. 状态模式(State Pattern)

意图:允许对象在内部状态改变时改变它的行为
适用场景:订单状态转换、游戏角色状态

interface OrderState {
    void handle(OrderContext context);
}

class NewState implements OrderState {
    public void handle(OrderContext context) {
        System.out.println("新订单,等待付款");
        context.setState(new PaidState());
    }
}

class PaidState implements OrderState {
    public void handle(OrderContext context) {
        System.out.println("已付款,准备发货");
        context.setState(new ShippedState());
    }
}

class OrderContext {
    private OrderState state;
    
    public OrderContext() {
        this.state = new NewState();
    }
    
    void setState(OrderState state) {
        this.state = state;
    }
    
    void process() {
        state.handle(this);
    }
}

// 使用
OrderContext order = new OrderContext();
order.process(); // 新订单 → 已付款
order.process(); // 已付款 → 已发货

Spring应用:StatefulSessionBean 状态管理
目的:消除大量条件判断,提高状态转换的可维护性

20. 访问者模式(Visitor Pattern)

意图:将算法与对象结构分离
适用场景:文档导出、编译器语法树分析

interface DocumentElement {
    void accept(Visitor visitor);
}

class TextElement implements DocumentElement {
    public void accept(Visitor visitor) {
        visitor.visit(this);
    }
}

class ImageElement implements DocumentElement {
    public void accept(Visitor visitor) {
        visitor.visit(this);
    }
}

interface Visitor {
    void visit(TextElement text);
    void visit(ImageElement image);
}

class HtmlExportVisitor implements Visitor {
    public void visit(TextElement text) {
        System.out.println("导出文本为HTML");
    }
    
    public void visit(ImageElement image) {
        System.out.println("导出图片为HTML");
    }
}

// 使用
List<DocumentElement> elements = Arrays.asList(
    new TextElement(), new ImageElement()
);

Visitor exporter = new HtmlExportVisitor();
elements.forEach(e -> e.accept(exporter));

Spring应用:BeanDefinitionVisitor 访问Bean定义
目的:在不修改对象结构的前提下定义新操作

21. 中介者模式(Mediator Pattern)

意图:用一个中介对象来封装一系列对象交互
适用场景:聊天室、机场调度系统

class ChatUser {
    private String name;
    private ChatMediator mediator;
    
    public ChatUser(String name, ChatMediator mediator) {
        this.name = name;
        this.mediator = mediator;
    }
    
    public void send(String message) {
        mediator.sendMessage(message, this);
    }
    
    public void receive(String message) {
        System.out.println(name + "收到消息:" + message);
    }
}

interface ChatMediator {
    void sendMessage(String msg, ChatUser user);
}

class ChatRoom implements ChatMediator {
    private List<ChatUser> users = new ArrayList<>();
    
    public void addUser(ChatUser user) {
        users.add(user);
    }
    
    public void sendMessage(String msg, ChatUser sender) {
        for (ChatUser user : users) {
            if (user != sender) {
                user.receive(msg);
            }
        }
    }
}

// 使用
ChatMediator mediator = new ChatRoom();
ChatUser user1 = new ChatUser("Alice", mediator);
ChatUser user2 = new ChatUser("Bob", mediator);
user1.send("大家好!");

Spring应用:ApplicationContext 作为Bean的中介者
目的:减少对象间直接耦合,集中控制交互逻辑

22. 迭代器模式(Iterator Pattern)

意图:提供统一的方式访问聚合对象中的元素
适用场景:集合遍历、树形结构访问

interface Iterator<T> {
    boolean hasNext();
    T next();
}

class Book {
    private String name;
    // 构造方法/getter/setter
}

class BookShelf implements Iterable<Book> {
    private Book[] books;
    private int index = 0;
    
    public BookShelf(int size) {
        books = new Book[size];
    }
    
    public void addBook(Book book) {
        books[index++] = book;
    }
    
    public Iterator<Book> iterator() {
        return new BookIterator();
    }
    
    private class BookIterator implements Iterator<Book> {
        private int position = 0;
        
        public boolean hasNext() {
            return position < books.length && books[position] != null;
        }
        
        public Book next() {
            return books[position++];
        }
    }
}

// 使用
BookShelf shelf = new BookShelf(3);
shelf.addBook(new Book("设计模式"));
shelf.addBook(new Book("Spring实战"));

for (Book book : shelf) {
    System.out.println(book.getName());
}

Spring应用:CompositeIterator 遍历组合结构
目的:统一遍历接口,隐藏集合内部实现

23. 解释器模式(Interpreter Pattern)

意图:定义语言的文法表示,并解释该语言中的句子
适用场景: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;
    private Expression expr2;
    
    public OrExpression(Expression expr1, Expression expr2) {
        this.expr1 = expr1;
        this.expr2 = expr2;
    }
    
    public boolean interpret(String context) {
        return expr1.interpret(context) || expr2.interpret(context);
    }
}

// 使用
Expression john = new TerminalExpression("John");
Expression married = new TerminalExpression("Married");
Expression expression = new OrExpression(john, married);

System.out.println("John is male? " + expression.interpret("John")); // true
System.out.println("Lucy is Married? " + expression.interpret("Married Lucy")); // true

Spring应用:SpEL(Spring Expression Language)表达式解析
目的:扩展领域特定语言(DSL)的处理能力

Spring框架行为模式应用总结

模式典型应用场景实现目标
策略模式ResourceLoader策略选择动态切换算法实现
模板方法JdbcTemplate操作流程复用固定流程,自定义扩展点
观察者模式ApplicationEvent事件机制松耦合事件驱动架构
责任链模式FilterChain处理HTTP请求灵活组合处理流程
命令模式事务管理封装支持事务的撤销/重做
状态模式状态机实现优雅处理状态转换逻辑

http://www.kler.cn/a/580186.html

相关文章:

  • 安固软件上网行为管理软件:提升企业效率与安全的双重保障
  • 【leetcode hot 100 2】两数相加
  • volatile 在 JVM 层面的实现机制
  • 时序分析
  • Hadoop安装文件解压报错:无法创建符号链接。。。
  • golang从入门到做牛马:第三篇-Go程序的“骨骼架构”
  • Jetson Xavier NX安装CUDA加速的OpenCV
  • Day04 模拟原生开发app过程 Androidstudio+逍遥模拟器
  • 安当TDE透明加密技术:为Manus大模型构建用户会话数据保护的“安全金库”
  • 软件工程:软件需求之需求分析方法
  • 深入理解string:从模拟实现看本质
  • 机器学习之KMeans算法
  • CI/CD—Jenkins配置Poll SCM触发自动构建
  • JSON.parse(JSON.stringify())深拷贝不会复制函数
  • 数据库1-2章
  • 【商城实战(18)】后台管理系统基础搭建:从0到1构建电商中枢
  • C++ 算法竞赛STL以及常见模板
  • 优选算法系列(1. 双指针_上)
  • DICOM医学影像脱敏技术应用的重要性及其实现方法详解
  • [Pytorch报错问题解决]AttributeError: ‘nn.Sequential‘ object has no attribute ‘append‘