设计模式-Map+函数式接口-策略模式-模板

56 篇文章 2 订阅
11 篇文章 0 订阅

目录

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实现类 - 腾讯云开发者社区-腾讯云

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值