Implement a simple factory pattern with Spring 3 annotations

前端 未结 11 2014
旧巷少年郎
旧巷少年郎 2020-12-12 10:37

I was wondering how I could implement the simple factory pattern with Spring 3 annotations. I saw in the documentation that you can create beans that call the factory class

11条回答
  •  再見小時候
    2020-12-12 11:28

    The following worked for me:

    The interface consist of you logic methods plus additional identity method:

    public interface MyService {
        String getType();
        void checkStatus();
    }
    

    Some implementations:

    @Component
    public class MyServiceOne implements MyService {
        @Override
        public String getType() {
            return "one";
        }
    
        @Override
        public void checkStatus() {
          // Your code
        }
    }
    
    @Component
    public class MyServiceTwo implements MyService {
        @Override
        public String getType() {
            return "two";
        }
    
        @Override
        public void checkStatus() {
          // Your code
        }
    }
    
    @Component
    public class MyServiceThree implements MyService {
        @Override
        public String getType() {
            return "three";
        }
    
        @Override
        public void checkStatus() {
          // Your code
        }
    }
    

    And the factory itself as following:

    @Service
    public class MyServiceFactory {
    
        @Autowired
        private List services;
    
        private static final Map myServiceCache = new HashMap<>();
    
        @PostConstruct
        public void initMyServiceCache() {
            for(MyService service : services) {
                myServiceCache.put(service.getType(), service);
            }
        }
    
        public static MyService getService(String type) {
            MyService service = myServiceCache.get(type);
            if(service == null) throw new RuntimeException("Unknown service type: " + type);
            return service;
        }
    }
    

    I've found such implementation easier, cleaner and much more extensible. Adding new MyService is as easy as creating another spring bean implementing same interface without making any changes in other places.

提交回复
热议问题