目录
1、背景
重构手法实际上是实现了装饰器模式,通过继承源类的方式实现类装饰器,而通过包装源类对象的方式实现对象装饰器,两种装饰器模式的实现,都增强了源对象的功能。
2、动机
3、做法
4、范例
5、真实工程案例
目前我们有一个类FkFkdZdsxService提供了一个方法,public RestResponse<List<FkZdsxFeginVO>> getFkdmbYmszList(FkFkdZdsxSelectDTO dto) throws SystemException
该类源码我们无法直接修改,而我们需要对该类进行增强,让该方法实现缓存功能,在这里我们通过类装饰器来实现了FkFkdZdsxService的装饰器FkFkdZdsxServiceCacheDecorator,客户端将原来调用FkFkdZdsxService对象地方,全部改成调用FkFkdZdsxServiceCacheDecorator对象,该装饰对象与原始目标对象其拥有相同的方法签名,构型相同,客户端是不需要进行变更的。
package cn.vetech.charge.fccost.service.fkzdsx;
import java.util.List;
import org.springframework.stereotype.Service;
import cn.vetech.charge.cloud.cache.annotation.Cache;
import cn.vetech.charge.cloud.common.ApplicationName;
import cn.vetech.charge.cloud.exception.SystemException;
import cn.vetech.charge.cloud.modules.utils.collection.CollectionUtil;
import cn.vetech.charge.cloud.springcloud.api.RestResponse;
import cn.vetech.charge.cloud.springcloud.util.RestResponseUtil;
import cn.vetech.charge.fccost.feign.fkzdsx.dto.FkFkdZdsxSelectDTO;
import cn.vetech.charge.fccost.feign.fkzdsx.vo.FkZdsxFeginVO;
/**
* FkFkdZdsxService缓存装饰器
* @author LiQiao
* @date 2022/05/06
*/
@Service
public class FkFkdZdsxServiceCacheDecorator extends FkFkdZdsxService {
/**
* 緩存名字
*/
private static final String CACHENAME = ApplicationName.FCCOST + "FkFkdZdsxServiceCacheDecorator";
@Override
@Cache(appname = CACHENAME, table = "getFkdmbYmszList", key = "{1.qybh}-{1.mbid}-{1.djlx}", expiremin = 30)
public RestResponse<List<FkZdsxFeginVO>> getFkdmbYmszList(FkFkdZdsxSelectDTO dto) throws SystemException {
RestResponse<List<FkZdsxFeginVO>> fkZdsxFeginVOListResponse = super.getFkdmbYmszList(dto);
if (RestResponseUtil.isSuccessfulAndHasResult(fkZdsxFeginVOListResponse)
&& CollectionUtil.isNotEmpty(fkZdsxFeginVOListResponse.getResult())) {
return fkZdsxFeginVOListResponse;
}
return null;
}
}