论怎么彻底干掉ifelse的策略模式怎么实现

此处还是基于spring容器实现的

此处的灵感来源于spring中自动配置bean

首先我们还是定义一个策略集合

public interface CalculateStrategy {
    
    

    /**
     * 角色
     */
    public String userType();

    /**
     * 算钱
     */
    public double discount(double fee);
}

策略实现

@Service
public class VipCalculateStrategy implements CalculateStrategy {
    
    
    @Override
    public String userType() {
    
    
        return "vip";
    }

    @Override
    public double discount(double fee) {
    
    
        return fee*0.8;
    }
}

正式使用

@Service
public class CalculateStrategyBiz {
    
    

    private Map<String , CalculateStrategy> map=new HashMap<>();

    public CalculateStrategyBiz(List<CalculateStrategy> calculateStrategyList) {
    
    
        for (CalculateStrategy calculateStrategy : calculateStrategyList) {
    
    
            map.put(calculateStrategy.userType(),calculateStrategy);
        }
    }

    public double sale(String userType , double fee){
    
    
        CalculateStrategy calculateStrategy=map.get(userType);
        return calculateStrategy.discount(fee);
    }
}

这样我们就可以根据不同的策略名称调取不同的策略,下面是spring中的实现

private final Map<String, Object> singletonObjects = new HashMap();

SimpleJndiBeanFactory#doGetSingleton(String name, @Nullable Class<T> requiredType) throws NamingException {
    
    
        synchronized(this.singletonObjects) {
    
    
            Object singleton = this.singletonObjects.get(name);
            if (singleton != null) {
    
    
                if (requiredType != null && !requiredType.isInstance(singleton)) {
    
    
                    throw new TypeMismatchNamingException(this.convertJndiName(name), requiredType, singleton.getClass());
                } else {
    
    
                    return singleton;
                }
            } else {
    
    
                T jndiObject = this.lookup(name, requiredType);
                this.singletonObjects.put(name, jndiObject);
                return jndiObject;
            }
        }
    }

在此处我们可以看到spring是通过一个map集合将所有单例bean存储的,之后我们getBean的时候直接通过bean的name调取对应的bean

猜你喜欢

转载自blog.csdn.net/cj181jie/article/details/108057080