首页 > 其他分享 >命令模式和模板模式以及构造者模式在工程中的应用

命令模式和模板模式以及构造者模式在工程中的应用

时间:2023-07-08 22:56:20浏览次数:35  
标签:userVo 模式 class _. 构造 import public 模板 page

  在开发springboot项目的开发过程中我们总会使用到mvc模式,在controller层写接口,service中写业务,dao层进行数据持久化。这种模式总会service的实现层写很多代码,这样会使得seviceimpl类中有很多业务代码,以及注入很多的bean,后期维护起来会相当麻烦。今天采用命令模式,模板模式来实现各业务接口的解耦。

1.Executor

public interface Executor {
    <R extends Receiver> R getReceiver(Class<R> clazz);

    default <T> T execute(Command<T> command) {
        return command.execute(this);
    }
}

2.Receiver

public interface Receiver {
}

3.CommanExecutor

@Component
@Transactional
public class CommandExecutor implements Executor {
    @Autowired(
        required = false
    )
    private Map<String, DomainService> domainServices;

    public CommandExecutor() {
    }

    public <R extends Receiver> R getReceiver(Class<R> clazz) {
        return (Receiver)this.domainServices.get(String_.lowerFirst(clazz.getSimpleName()));
    }

    public Map<String, DomainService> getDomainServices() {
        return this.domainServices;
    }
}

4.DomainService

public interface DomainService extends Receiver {
}

5.DomainServiceImpl

public class DomainServiceImpl implements DomainService {
    public DomainServiceImpl() {
    }
}

6.CommandQry

public abstract class CommonQry<T> implements Command<T> {
    private static final Logger log = LoggerFactory.getLogger(CommonQry.class);
    protected Integer pageNo = (Integer)ThreadLocal_.get("page_param_offset_page");
    protected Integer pageSize = (Integer)ThreadLocal_.get("page_param_offset_size");
    protected Boolean isSensitized;
    protected LambdaQueryWrapper queryWrapper;

    public CommonQry() {
        this.isSensitized = Boolean.FALSE;
    }

    protected <E extends BaseEntity, R extends BaseMapper> List<E> paginate(Class<R> clazz) {
        IPage page = null;

        try {
            Method method = clazz.getMethod("selectPage", IPage.class, Wrapper.class);
            if (Object_.isNotEmpty(page = (IPage)method.invoke(Spring_.getBean(clazz), this.page(), this.queryWrapper))) {
                if (PageHelper.pageable() && !String_.equals(PageHelper.getPageType(), "cursor")) {
                    ThreadLocal_.set("page_total_number", page.getTotal());
                }

                if (!this.isSensitized) {
                    return page.getRecords();
                }

                this.desensitized(page.getRecords());
            }

            return page.getRecords();
        } catch (Exception var4) {
            throw new BusinessException(ErrorEnum.E881);
        }
    }

    protected <E> E desensitized(E e) {
        Field[] fields = e.getClass().getDeclaredFields();
        Field[] var3 = fields;
        int var4 = fields.length;

        for(int var5 = 0; var5 < var4; ++var5) {
            Field field = var3[var5];
            field.setAccessible(true);

            try {
                CcbDesensitizedUtil.setNewValueForField(e, field, field.get(e));
            } catch (Exception var8) {
                throw new BusinessException("数据脱敏失败");
            }
        }

        return e;
    }

    protected <E> List<E> desensitized(List<E> lists) {
        Iterator var2 = lists.iterator();

        while(var2.hasNext()) {
            E record = var2.next();
            this.desensitized(record);
        }

        return lists;
    }

    protected Page page() {
        return new Page(this.pageNo == null ? 1L : (long)this.pageNo, this.pageSize == null ? 10L : (long)this.pageSize);
    }
}

7.baseApi

public class BaseApi {
    @Autowired(
        required = false
    )
    protected CommandExecutor commandExecutor;
    @Autowired(
        required = false
    )
    protected QueryExecutor queryExecutor;

    public BaseApi() {
    }

    @ApiResult
    @Operation(
        summary = "测试联通性",
        description = "请求接口前可调用该接口测试接口是否活着"
    )
    @GetMapping({"/isalive"})
    public String isAlive() {
        return "ok";
    }

8.使用案列,本案中我们将数据查询的接口独立成为一个类,这样我们就实现了将复杂代码从业务模块中独立出来了

@RestController
@RequestMapping("/api/user")
@Tag(name = "用户管理",description = "用户管理")
public class SysUserApi extends BaseApi {
    public static final String[] VALID_FIELD = {"userNo","email","mobile"};

    @Pagination
    @PostMapping("/list")
    @ApiResult(successCode = 200,successMsg = "查询成功")
    @PreAuthorize("hasAuthority('system:user:list')")
    @Operation(summary = "用户列表查询",description = "用户列表查询")
    public List<SysUser> list(@RequestBody SysUserVo userVo) {
        return commandExecutor.execute(SysUserQry.builder().userVo(userVo).build());
    }

    @PostMapping("/add")
    @PreAuthorize("hasAuthority('system:user:add')")
    @ApiResult(successCode = 200,successMsg = "操作成功")
    @Operation(summary = "新增用户",description = "新增用户")
    public void add(@RequestBody @Validated({Create.class}) SysUserDto userDto) {
        SysUser user = UserMapper.USER_MAPPER.toEntity(userDto);
        commandExecutor.getReceiver(SysUserManager.class).duplicationValid(user,VALID_FIELD);
        userDto.setPassword();
        commandExecutor.execute(new SysUserCmd(userDto));
    }

    @PostMapping("/update")
    @ApiResult(successCode = 200,successMsg = "操作成功")
    @Operation(summary = "修改用户",description = "修改用户")
    @PreAuthorize("hasAuthority('system:user:update')")
    public void update(@RequestBody @Validated({Update.class}) SysUserDto userDto) {
        SysUser user = UserMapper.USER_MAPPER.toEntity(userDto);
        if (Object_.isNotEmpty(user.getId())) {
            commandExecutor.getReceiver(SysUserManager.class).findById(user.getId()).ifPresent(bean -> {
                commandExecutor.getReceiver(SysUserManager.class).duplicationValid(user,VALID_FIELD);
                commandExecutor.execute(new SysUserCmd(userDto.getId(),userDto));
            });
        }
    }

    @GetMapping("/deleteById/{ids}")
    @ApiResult(successCode = 200,successMsg = "操作成功")
    @Operation(summary = "删除用户",description = "删除用户")
    @PreAuthorize("hasAuthority('system:user:delete')")
    public void deleteByIds(@PathVariable("ids") String ids) {
        List<Long> longIds = new ArrayList<>();
        for (String s : ids.split(",")) {
            Long id = Long.parseLong(s);
            commandExecutor.getReceiver(SysUserManager.class).findById(id).ifPresent(user -> {
                longIds.add(id);
            });
        }
        commandExecutor.getReceiver(SysUserManager.class).remove(longIds);
    }
}
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bit.common.command.Executor;
import com.bit.common.core.command.CommonQry;
import com.bit.common.model.Authentication;
import com.bit.common.utils.AuthenticationHolder;
import com.bit.common.utils.Object_;
import com.bit.common.utils.String_;
import com.nii.admin.domain.entity.SysUser;
import com.nii.admin.domain.repository.SysUserDao;
import com.nii.admin.infra.utils.List_;
import com.nii.model.vo.SysUserVo;
import lombok.Builder;
import lombok.Data;

import java.util.List;

@Data
@Builder
public class SysUserQry extends CommonQry<List<SysUser>> {
    private SysUserVo userVo;

    @Override
    public List<SysUser> execute(Executor executor) {
        isSensitized = true;
        queryWrapper = new LambdaQueryWrapper<SysUser>()
                .eq(Object_.isNotEmpty(userVo.getSex()), SysUser::getSex, userVo.getSex())
                .eq(Object_.isNotEmpty(userVo.getState()), SysUser::getState, userVo.getState())
                .eq(Object_.isNotEmpty(userVo.getDeptId()), SysUser::getDeptId, userVo.getDeptId())
                .like(String_.isNotEmpty(userVo.getUserNo()), SysUser::getUserNo, userVo.getUserNo())
                .like(String_.isNotEmpty(userVo.getMobile()), SysUser::getMobile, userVo.getMobile())
                .like(String_.isNotEmpty(userVo.getEmail()), SysUser::getEmail, userVo.getEmail())
                .like(String_.isNotEmpty(userVo.getUserName()), SysUser::getUserName, userVo.getUserName());
        return this.paginate(SysUserDao.class);
    }
}

  

标签:userVo,模式,class,_.,构造,import,public,模板,page
From: https://www.cnblogs.com/Eastern-Towns/p/17538052.html

相关文章

  • c++模板相关学习--泛型编程
     类模板基础#define_CRT_SECURE_NO_WARNINGS#include<iostream>usingnamespacestd;#include<string>template<classNAMETYPE,classAGETYPE=int>//类模板中可以有默认参数classPerson{public:Person(NAMETYPEname,AGETYPEage){......
  • Hadoop 伪分布模式配置
    etc/hadoop/core-site.xml<configuration><!--指定HDFS中namenode地址--><property><name>fs.defaultFS</name><value>hdfs://hadoop01:9000</value></property><!--指定Hadoop运行时......
  • [模板]01trie,维护异或最大值
    //查询异或最大值,每次插入和查询时间都是log(C)template<classT>classtrie01{vector<vector<T>>tree;public:trie01():tree(1,vector<T>(2,0)){}//插入待检查的数字voidinsert(Tx){intp=0;for(inti=sizeof......
  • OSG 使用整理(5):模板测试与边缘效果
    osg使用整理(5):模板测试与边缘效果1模板测试​ 在渲染管线中,模板测试在片段着色器后执行,通过像素与模板缓冲中的模板值比较,选择性丢弃或者保存这个像素颜色。我们可以通过更新模板测试来获得一些很有意思的效果。下图为LearnOpenGL网站一个例子。​ 可以发现,颜色缓冲经过模......
  • 15款最佳的HTML5移动模板
    如果你需要响应式和前端开发,那么HTML5是你务必要学会的Web开发语言。我们在Codecondo上发布的HTML5相关文章依然很受欢迎。例如:为HTML5开发者准备的40个工具、针对HTML5的Web框架,你一定要看看它们,我也相信它们会成为你书签的其中之一。当人们上网搜索登陆页面的时候,他们大多是寻......
  • P3378 【模板】二叉堆
    [洛谷]P3378【模板】堆方法一手写堆最小堆插入从新增的最后一个结点的父结点开始,用要插入元素向下过滤上层结点(相当于要插入的元素向上渗透)voidsiftdown(inti)//传入一个需要向下调整的结点编号i,这里传入1,即从堆的顶点开始向下调整{intt,flag=0;//flag用来标......
  • 洛谷题解——【模板】堆
    题目链接:【模板】堆【模板】堆题目描述给定一个数列,初始为空,请支持下面三种操作:给定一个整数\(x\),请将\(x\)加入到数列中。输出数列中最小的数。删除数列中最小的数(如果有多个数最小,只删除\(1\)个)。输入格式第一行是一个整数,表示操作的次数\(n\)。接下来\(n\)......
  • 介绍Vue router的history模式以及如何配置history模式
    引言Vuerouter给我们提供了两种路由模式,分别是hash模式和history模式。其中默认是使用hash模式,即URL中带有一个#符号,但是处于业务或个人喜爱的差别,Vuerouter也提供了history模式。但是由于Vue是单页SPA应用,所以每个路由并没有对应的html文件。什么是history模式history模式特......
  • C语言单例模式
    单例模式的定义​ 单例模式的需求是保证在代码的整个运行期间,某种数据类型只有一个唯一的实例子。并且提供一个全局的访问接口。我们可以从两个角度来理解单例模式数据类型有且仅可以创建一个实例,编程人员不可以的随意的定义的此类型的实例。我们必须限制这种数据结构的创建。......
  • C++黑马程序员——P189-192. string容器 构造函数,赋值,拼接,查找和替换
    P189.string容器——构造函数P190....——赋值操作P191....——字符串拼接P192....——字符串查找和替换P189.构造函数———————————————————————————————————————————————————————————————......