On how to completely kill the ifelse strategy mode and how to realize

Here is still based on spring container implementation

The inspiration here comes from the automatic configuration of beans in spring

First of all, we still define a strategy set

public interface CalculateStrategy {
    
    

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

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

Strategy implementation

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

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

official use

@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);
    }
}

In this way, we can call different strategies according to different strategy names. The following is the implementation in 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;
            }
        }
    }

Here we can see that spring stores all singleton beans through a map collection, and then when we getBean, we directly retrieve the corresponding bean through the bean name

Guess you like

Origin blog.csdn.net/cj181jie/article/details/108057080