目录

1、使用函数式接口

2、使用枚举+工厂类

3、使用注解实现策略模式


目的:解决大量使用 if else 的场景

1、使用函数式接口

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;

/**
 * @Description: 字典服务类
 */
@Slf4j
@Service
@AllArgsConstructor
public class DictService {

    final XXXService xxxService;

    private Map<String, Function<String, List>> dictMap = new HashMap<>();

    /**
     * @Description 根据type获取对应的字典
     */
    public List getDictMapByType(String type) {
        Function<String, List> result = dictMap.get(type);
        if (result != null) {
            //执行这段表达式获得String类型的结果
            return result.apply(type);
        }
        return null;
    }

    /**
     * 初始化业务逻辑,其中value 存放的是 lambda表达式
     */
    @PostConstruct
    public void initDictMap() {
        dictMap.put("xx_字典1", dictType -> getEnumByType(dictType));
        dictMap.put("xx_字典2", dictType -> getEnumByType(dictType));
        dictMap.put("xx_字典3", dictType -> xxxService.getXXListByType());
    }

    /**
     * @Description 获取字典
     */
    public List getEnumByType(String type) {
		//自定义各种操作
        return null;
    }

}

2、使用枚举+工厂类

工厂类:

/**
 * 索引工厂
 */
public interface IndexFactory {
    AccountVo getResponse(String source);
    Map<String, Float> keywordFields();
}

如果有很多if else判断,需要封装参数等场景,可以使用此方式减少if else

枚举类:

public enum IndexEnum implements IndexFactory {

	TEST("测试", "test") {
		@Override
		public AccountVo getResponse(String source) {
			return GSON.fromJson(source, AccountVo.class);
		}

		@Override
		public Map<String, Float> keywordFields() {
			HashMap<String, Float> fields = Maps.newHashMap();
			fields.put(EsConstant.FIELD_AUTHOR_NAME_ITPA, AbstractQueryBuilder.DEFAULT_BOOST);
			fields.put(EsConstant.FIELD_AUTHOR_DESC_ITPA, AbstractQueryBuilder.DEFAULT_BOOST);
			return fields;
		}
	},;

	private String chName;
	private String testIndex;

	private static final Gson GSON = new GsonBuilder().create();


	Index(String chName, String testIndex) {
		this.chName = chName;
		this.testIndex = testIndex;
	}

	public String chName() {
		return chName;
	}

	public String testIndex() {
		return testIndex;
	}

}

3、使用注解实现策略模式

Spring Boot 使用策略模式指定Service实现类 - 腾讯云开发者社区-腾讯云

Logo

技术共进,成长同行——讯飞AI开发者社区

更多推荐