策略模式+工厂模式+spring后置处理器干掉ifelse

主要是通过spring的InitializingBean接口的afterPropertiesSet()方法

这个例子只是一个思想,感觉没有实际的用途。

主要是通过spring的InitializingBean接口的afterPropertiesSet()方法

凡是继承InitializingBean接口的类在初始化Bean的时候都会去执行afterPropertiesSet()方法,我们就可以利用这个特点将不同条件的类放到一个map中,条件当作key,调用的时候就不需要用if(条件){return value},只需要map.get(条件)就可以获取到想要的值了。

这个例子只是一个思想,感觉没有实际的用途。

public interface GetKey {

    int getKey();

}

@RestController

public class MyController {

    @GetMapping("/killiftest")

    public int killif(int i){

        GetKey key = MyFactory.getKey(i);

        return key.getKey();

    }

}

public class MyFactory {

    public static Map<Integer,GetKey> map = new ConcurrentHashMap<>();

    public static GetKey getKey(Integer type){

        return map.get(type);

    }

    public static void register(Integer type,GetKey getKey){

        map.put(type,getKey);

    }

}

@Component

public class OneGetKey implements GetKey, InitializingBean {

    @Override

    public int getKey() {

        return 1;

    }

    @Override

    public void afterPropertiesSet() throws Exception {

        MyFactory.register(1,this);

    }

}

@Component

public class TwoGetKey implements GetKey, InitializingBean {

    @Override

    public int getKey() {

        return 2;

    }

    @Override

    public void afterPropertiesSet() throws Exception {

        MyFactory.register(2,this);

    }

}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。