策略模式demo

策略模式

代码中使用大量if 使用策略优化

将不同的业务需求类 整合成一个接口

通过多个实现类实现业务代码的拆分

1、定义一个公用的接口

import com.spring.Component;

@Component
public interface ImgZipStrategy {

    
    /**
     * 获取不同策略的标识
     */
    String getZipType();

    /**
     * 封装公用算法
     */
    String zipWork(ImgCompressQO qo);
}

2、定义不同的实现策略

以图片压缩为例子 数据源分为了 base64、文件路径、url

2.1 数据源为base64 实现的实现类

import com.spring.Component;

/**
 * Base64格式的图片压缩 策略 
 */
@Component
public class ImgZipByBase64Impl implements ImgZipStrategy {

    @Override
    public String getZipType() {
        return "base64业务逻辑";
    }

    @Override
    public String zipWork(ImgCompressQO qo) {
        return "base64处理逻辑";
    }

}

2.2 数据源为filePath实现的实现类

import com.spring.Component;

/**
 * 文件路径的图片压缩 策略 
 */
@Component
public class ImgZipByFilePathImpl implements ImgZipStrategy {

    @Override
    public String getZipType() {
        return "flilePath处理逻辑";
    }

    @Override
    public String zipWork(ImgCompressQO qo) {
        return "flilePath处理逻辑";
    }

}

2.3 数据源为Url实现的实现类

import com.spring.Component;

/**
 * Url格式的图片压缩 策略 
 */
@Component
public class ImgZipByUrlhImpl implements ImgZipStrategy {

    @Override
    public String getZipType() {
        return "flilePath处理逻辑";
    }

    @Override
    public String zipWork(ImgCompressQO qo) {
        return "flilePath处理逻辑";
    }

}

3.入口

3.1 通过实现 ApplicationContextAware 初始化的时候加载所有策略的实现类。

3.2 维护内部Map Key为实现类的标识,V为接口类型。

3.3 通过入参,执行不同的策略逻辑。

@Component
public class ImgZipService implements ApplicationContextAware {

    @Resource
    private final Map<String, ImgZipStrategy> imgZipStrategyMap = new ConcurrentHashMap<>();

    public CommonResult doImgZip(ImgCompressQO qo) {

        //通过入参传递对应的实现标识 拿到对应的策略实现类
        ImgZipStrategy imgZipStrategy = imgZipStrategyMap.get(qo.getSrcDataType);
        
        //调用对应的实现类的方法
        imgZipStrategy.zipWork(qo);
    }

        @Override
        public void setApplicationContext (ApplicationContext applicationContext) throws BeansException {     
        //将不同的策略放入到map中
            Map<String, ImgZipStrategy> beansOfType = applicationContext.getBeansOfType(ImgZipStrategy.class);
            beansOfType.values().forEach(imgZipStrategy -> imgZipStrategyMap.put(imgZipStrategy.getZipType(), imgZipStrategy));
        }
    }

}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值