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

本文介绍如何通过策略模式在Spring Boot应用中,避免大量if-else,提高代码可读性。通过定义接口、具体业务类和策略类,实现根据不同参数动态调用生成目录或封面的逻辑。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前言

在我们平时开发业务过程中经常会遇到很多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();
}

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

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值