使用策略模式结合InitializingBean或ApplicationContextAware简化if-else

前言

在我们平时开发业务过程中经常会遇到很多if-else的判断情况,需要根据不同的情况或者不同的参数走不同的逻辑,所以大量的if-else非常的麻烦,代码十分不美观,所以可以通过相关方法解决这个问题。

使用步骤

以生成文书为例,现在有一个根据不同的参数生成不同文书的需求

一、定义生成文书接口
package com.example.demo.simplifyIfElse;

/**
 * @description: 生成文书接口
 * @author: hbc
 * @date: 2022-07-14 15:36
 */

public interface Document {
    /**
     * 文书类型
     * @return
     */
    Integer getType();
    /**
     * 生成文书
     */
    void createDocument();
}
二、编写具体业务实现类
1、生成目录实现类
package com.example.demo.simplifyIfElse;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * @description: 生成目录具体业务类
 * @author: hbc
 * @date: 2022-07-14 15:36
 */
@Slf4j
@Component
public class CatalogImpl implements Document {

    @Override
    public Integer getType() {
        return 2;
    }

    /**
     * 具体业务
     */
    @Override
    public void createDocument() {
        log.info("执行生成目录具体业务类");
    }
}
2、生成封面实现类
package com.example.demo.simplifyIfElse;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * @description: 生成封面具体业务类
 * @author: hbc
 * @date: 2022-07-14 15:36
 */
@Slf4j
@Component
public class CoverImpl implements Document {

    @Override
    public Integer getType() {
        return 1;
    }

    /**
     * 具体业务
     */
    @Override
    public void createDocument() {
        log.info("执行生成封面具体业务类");
    }
}
三、编写策略类
package com.example.demo.simplifyIfElse;

import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * @description: 生成文书策略类
 * @author: hbc
 * @date: 2022-07-14 15:39
 */
@Slf4j
@Component
public class DocumentRouteInitialize implements InitializingBean {

    private final static EmptyDesc EMPTY = new EmptyDesc();

    private static final Map<Integer, Document> routerMap = Maps.newHashMap();

    @Autowired
    private List<Document> documentList;

    @Override
    public void afterPropertiesSet() throws Exception {
        for (Document service : documentList) {
            routerMap.put(service.getType(), service);
        }
    }
    public Document getService(Integer type) {
        Document document = routerMap.get(type);
        return Optional.ofNullable(document).orElse(EMPTY);
    }

    /**
     * 未知的响应
     */
    private static class EmptyDesc implements Document {
        @Override
        public Integer getType() {
            return null;
        }
        @Override
        public void createDocument() {
            log.error("类型错误,生成文书失败");
        }
    }
}

或者使用Sping容器提供的接口简化if-else。

package com.example.demo.simplifyIfElse;

import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import java.util.Map;

/**
 * @description: 生成文书管理类
 * @author: hbc
 * @date: 2022-07-14 15:39
 */
@Slf4j
@Component
public class DocumentRouteApplicationContextAware implements ApplicationContextAware {

    private ApplicationContext applicationContext;


    private static final Map<Integer, Document> routerMap = Maps.newHashMap();

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
        // 准备 Document 的所有实现类
        prepareDocument();
    }


    private void prepareDocument() {
        // 获取容器中所有生成文书的实现类
        Map<String, Document> documentMap = this.applicationContext.getBeansOfType(Document.class);
        documentMap.forEach((key, value) -> {
            routerMap.put(value.getType(), value);
        });
    }

    public static Document getDocument(Integer type) {
        return routerMap.get(type);
    }

}
四、测试
@Autowired 
private DocumentRouteInitialize documentRouteInitialize;
@Test
public void simpleIfElse(){
    Document service = documentRouteInitialize.getService(1);
    service.createDocument();
    Document document = DocumentRouteApplicationContextAware.getDocument(2);
    document.createDocument();
}

效果:
在这里插入图片描述
参数可以自定义在配置文件中或者常量等形式更加灵活。

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
策略模式和工厂模式可以搭配使用,以解决策略模式中的一些缺陷。在策略模式中,我们可以使用工厂方法模式来明确返回对象的信息。具体实现可以分为以下几个步骤: 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 ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值