Autowired实现策略模式

1. 创建Springboot项目

2. 创建策略接口类

public interface TwoHandler {
    /**
     * 判断策略类型
     * @param type
     * @return
     */
    boolean accept(String type);

    /**
     * 策略逻辑方法
     */
    void handler();
}

3. 创建具体策略类

@Service
public class Handler1 implements TwoHandler{
    @Override
    public boolean accept(String type) {
        return "handler1".equals(type);
    }

    @Override
    public void handler() {
        System.out.println("Handler1处理完成");
    }
}
@Service
public class Handler2 implements TwoHandler{
    @Override
    public boolean accept(String type) {
        return "handler2".equals(type);
    }

    @Override
    public void handler() {
        System.out.println("Handler2处理完成");
    }
}

4. 创建策略使用门面

@Component
public class TwoContext {
    @Autowired
    private List<TwoHandler> handlerList;

    public void handle(String type){
        TwoHandler handler = Optional.ofNullable(handlerList).orElseGet(null)
                .stream().filter(h -> h.accept(type))
                .findFirst().orElse(null);
        if(handler == null){
            throw new RuntimeException("can not find handler");
        }
        handler.handler();
    }
}

5. 使用

@SpringBootTest
class ApplicationTests {

    @Autowired
    private TwoContext twoContext;
    @Test
    void contextLoads() {
        twoContext.handle("handler1");
    }
}

输出

Handler1处理完成
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值