策略模式如果如何把初始化要运行的类

1、静态代码块

public class OperateFactory {
    private static Map operationMap = new HashMap<>();

    static {

        operationMap.put("add", new AddOperate());

        operationMap.put("sub", new SubOperate());

        operationMap.put("multi", new multiOperate());

    }

}

2、SpringBoot 实践运用- implement ApplicationContextAware

@Component
public class AddOperate implements Operate {

    @Override
    public String operateType() {
        return "add";
    }

    @Override
    public Integer execute(int a, int b) {
        return a + b;
    }
}
@Component
public class OperateFactory implements ApplicationContextAware {
    private static Map operationMap = new HashMap<>();


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map tempMap = applicationContext.getBeansOfType(Operate.class);
        tempMap.values().forEach(source -> operationMap.put(source.operateType(), source));
    }

}

3、SpringBoot 实践运用-用一个存放所有的接口实现类

Spring的IOC容器启动时如果一个接口有多个实现类时,Spring会自动将接口的实现类注入到这个Map中,key为bean id,value值则为对应的策略实现类。我们只需要通过@Autowired注入对象,操作如下:

public class OperateFactory  {


    /**
     * Spring会自动将Operate接口的实现类注入到这个Map中,key为bean id,value值则为对应的策略实现类
     */
    @Autowired
    private Map operateMap;

}

你可能感兴趣的:(策略模式)