装饰器模式在Spring中的案例

设计模式-装饰器模式

装饰器模式所解决的问题是,在不改变原来方法代码的情况下对方法进行修饰,从而丰富方法功能。

Spring架构中的装饰器模式

在Spring架构中,以线程池进行举例。

线程池

线程池是一个对线程集中管理的对象,集中管理线程的创建和销毁以及调度。线程池中的线程所要执行的,就是传入线程池的任务,线程池安排线程对任务进行执行。

任务就是编码者想要交给线程池来执行的代码块,如果编码者想要给任务加上一些修饰,线程池便提供了修饰类入口。编码者可以在任务执行前后进行日志打印,线程变量设置或释放。

一般线程池配置

java 复制代码
import com.config.decorator.ThreadTaskDecorator;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

@Configuration
public class ThreadPoolConfig {
	@Bean("taskExecutor")
    public Executor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(10);
        executor.setMaxPoolSize(100);
        executor.setQueueCapacity(100);
        executor.setKeepAliveSeconds(60);
        executor.setTaskDecorator(new ThreadTaskDecorator());
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        return executor;
    }
}

线程装饰器

类ThreadTaskDecorator实现了接口TaskDecorator的decorate方法,对原任务进行了装饰。

java 复制代码
import org.springframework.core.task.TaskDecorator;

public class ThreadTaskDecorator implements TaskDecorator {

    @Override
    public Runnable decorate(Runnable runnable) {

        return () -> {
            //前置
            try {
            //前置
                runnable.run();//原任务
            }finally {
                //后置
            }
            //后置
        };
    }
}

线程池初始化--装饰器模式体现

初始化代码来自类ThreadPoolTaskExecutor.class,对无关代码进行了折叠。

java 复制代码
protected ExecutorService initializeExecutor(ThreadFactory threadFactory, RejectedExecutionHandler rejectedExecutionHandler) {
        ...
        ThreadPoolExecutor executor = new ThreadPoolExecutor(this.corePoolSize, this.maxPoolSize, (long)this.keepAliveSeconds, TimeUnit.SECONDS, queue, threadFactory, rejectedExecutionHandler) {
            public void execute(Runnable command) {
                Runnable decorated = command;
                if (ThreadPoolTaskExecutor.this.taskDecorator != null) {
                    decorated = ThreadPoolTaskExecutor.this.taskDecorator.decorate(command);
                    if (decorated != command) {
                        ThreadPoolTaskExecutor.this.decoratedTaskMap.put(decorated, command);
                    }
                }

                super.execute(decorated);
            }

            .
            .
            .
        };
        
        .
        .
        .
        
        return executor;
    }

从初始化代码中可以看见,在创建executor时对ThreadPoolExecutor的父类接口Executor中的execute方法进行了实现,其中就是判断任务装饰器taskDecorator不为空的情况下,调用taskDecorator对象的decorate方法对command即原任务 进行装饰。这里的taskDecorator对象就是我们前面通过nre ThreadTaskDecorator()传递进去的,在线程池初始化的时候被调用到decorate,对原任务进行装饰。

复制代码
装饰器模式是将装饰和被装饰者进行分离,装饰和被装饰者相互独立。这种分离的方式使得,一种装饰只需要实现一次,便可以重复使用。这是代码复用的很好方案。

类图

超父类 :实现 超父类 :实现 实现 Executor execute(Runnable command) ThreadPoolTaskExecutor TaskDecorator taskDecorator initializeExecutor() ThreadPoolExecutor <<interface>> TaskDecorator Runnable decorate(Runnable command) ThreadTaskDecorator Runnable decorate(Runnable command) ThreadPoolConfig Executor taskExecutor()

相关推荐
wno70419 分钟前
Spring Security权限控制
java·python·spring
杨运交1 小时前
[071][验证码模块]基于Spring拦截器的验证码认证设计思想
java·后端·spring
Geek-Chow1 小时前
CountDownLatch in Java
java
SL_staff2 小时前
从RBAC到场景化授权:《无忧·企业文档》三级权限模型的技术实践解析
java·开源·产品
传奇开心果编程2 小时前
【springboot基础语法学与练】第 1 课:从零开始
java·spring boot·后端·学习
SL_staff2 小时前
财务系统慎用低代码?从数据模型闭环看合规落地的技术实践
java·低代码·全栈
滕州市燕猫虎计算机科技工作室个体工商户3 小时前
IDEA:Command line is too long
java·ide·intellij-idea
步行cgn3 小时前
Spring p 命名空间注入详解
java·前端·spring
YatHinLay3 小时前
MyBatis 流式查询实战:ResultHandler 处理海量数据
java
天天被压力3 小时前
【跨市场数据实战 #08】可转债折价机会怎么筛:3个接口抓比价、列表和实时盘口
java·人工智能·python