使用InitializingBean实现策略模式

1. 创建SpringBoot项目

2. 创建抽象类AbstractThreeHandler

public abstract class AbstractThreeHandler implements InitializingBean {

    @Autowired
    private HandlerContext handlerContext;


    public abstract boolean accept(String type);

    public abstract void handler();

    @Override
    public void afterPropertiesSet() throws Exception {
        handlerContext.register(this);
    }
}

3. 创建策略具体类

@Service
public class Handler31 extends AbstractThreeHandler {
    @Override
    public boolean accept(String type) {
        return "handler31".equals(type);
    }

    @Override
    public void handler() {
        System.out.println(Handler31.class.getSimpleName()+"处理完成");
    }
}
@Service
public class Handler32 extends AbstractThreeHandler {
    @Override
    public boolean accept(String type) {
        return "handler32".equals(type);
    }

    @Override
    public void handler() {
        System.out.println(Handler32.class.getSimpleName()+"处理完成");
    }
}

4. 创建获取策略类

@Component
public class HandlerContext{

    private List<AbstractThreeHandler> handlers = new ArrayList<>();
    void register(AbstractThreeHandler handler){
        handlers.add(handler);
    }

    public AbstractThreeHandler getHandler(String type){
        AbstractThreeHandler handler = handlers.stream()
                .filter(h -> h.accept(type))
                .findFirst()
                .orElse(null);
        if(handler == null){
            throw new RuntimeException("can not find handler");
        }
        return handler;
    }
}

5. 使用

	private HandlerContext handlerContext;
    @Test
    void contextLoads() {
        handlerContext.getHandler("handler32").handler();
    }

结果:

Handler32处理完成
策略模式和工厂模式可以搭配使用,以解决策略模式中的一些缺陷。在策略模式中,我们可以使用工厂方法模式来明确返回对象的信息。具体实现可以分为以下几个步骤: 1. 定义策略的接口,包括策略抽象方法。 2. 创建各个实现策略接口的具体策略实现。 3. 使用组合的方式,将抽象接口的实现作为参数创建一个容器。 4. 在策略实现中加入信息标签,可以使用枚举的type值作为标签的载体。 5. 使用一个map对象作为容器的参数,将标签和对应的策略实现进行一一对应关系。 6. 在具体的策略实现中继承InitializingBean接口,并重写其中的afterPropertiesSet方法,在该方法中将含有信息的type和具体的策略实现放入容器的map中。 7. 最后,通过容器的map和标签,可以根据需要获取对应的策略实现使用工厂模式结合策略模式,不仅避免了大量的if-else判断,还能明确策略的返回信息,解决了策略模式的一些缺陷。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [Java 策略模式+工厂方法模式搭配思想](https://blog.csdn.net/weixin_44284706/article/details/124967861)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值