【设计模式之策略模式-实战】

设计模式之策略模式

1 编写接口
package strategy.impl;

import enums.ComputeTypeEnum;

public interface ComputeStrategy{
	Integer execute(Integer a,Integer b);
	ComputeTypeEnum applyFor();
}
2 枚举类
package enums;

import lombok.AllArgsConstructor;
import lombok.Getter;
import java.util.Objects;

@Getter
@AllArgsConstructor
public enum ComputeTypeEnum {
    ADD(1, "加法"),
    SUB(2, "减法"),
    MULTIPLY(3, "乘法"),
    DIV(4, "除法");
    private final Integer code;
    private final String desc;

    public static ComputeTypeEnum getCode(Integer code) {
        for (ComputeTypeEnum item : values()) {
            if (Objects.equals(item.getCode(), code)) {
                return item;
            }
        }
        return null;
    }
}
3编写策略
package strategy.impl;

import enums.ComputeTypeEnum;

public class AddStrategy implements ComputeStrategy{
	@Override
	Integer execute(Integer a,Integer b){
		return a+b;
	}
	@Override
	ComputeTypeEnum applyFor(){
		return ComputeTypeEnum.ADD;
	}
}
public class SubStrategy implements ComputeStrategy {
    @Override
    public Integer execute(Integer a, Integer b) {
        return a - b;
    }

    @Override
    public ComputeTypeEnum applyFor() {
        return ComputeTypeEnum.SUB;
    }
}
4 使用策略
import org.springframework.context.ApplicationContextAware;
import com.google.common.collect.Maps;
public Class IntegerCompute implements ApplicationContextAware{
	private Map<ComputeTypeEnum,ComputeStrategy> strategyMap = Maps.newHashMap();
	
	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException{
		Map<String,ComputeStrategy> map = applicationContext.getBeansOfType(ComputeStrategy.class);
		for(ComputeStrategy strategy : map.values()){
			strategyMap.put(strategy.applyFor(),strategy);
		}
	}
	public Integer compute(Integer a,Integer b,ComputeTypeEnum type){
		ComputeStrategy strategy= strategyMap.get(type);
		rerurn strategy.compute(a,b);
	}
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值