Implement a simple factory pattern with Spring 3 annotations

前端 未结 11 2016
旧巷少年郎
旧巷少年郎 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:04

    You are right, by creating object manually you are not letting Spring to perform autowiring. Consider managing your services by Spring as well:

    @Component
    public class MyServiceFactory {
    
        @Autowired
        private MyServiceOne myServiceOne;
    
        @Autowired
        private MyServiceTwo myServiceTwo;
    
        @Autowired
        private MyServiceThree myServiceThree;
    
        @Autowired
        private MyServiceDefault myServiceDefault;
    
        public static MyService getMyService(String service) {
            service = service.toLowerCase();
    
            if (service.equals("one")) {
                return myServiceOne;
            } else if (service.equals("two")) {
                return myServiceTwo;
            } else if (service.equals("three")) {
                return myServiceThree;
            } else {
                return myServiceDefault;
            }
        }
    }
    

    But I would consider the overall design to be rather poor. Wouldn't it better to have one general MyService implementation and pass one/two/three string as extra parameter to checkStatus()? What do you want to achieve?

    @Component
    public class MyServiceAdapter implements MyService {
    
        @Autowired
        private MyServiceOne myServiceOne;
    
        @Autowired
        private MyServiceTwo myServiceTwo;
    
        @Autowired
        private MyServiceThree myServiceThree;
    
        @Autowired
        private MyServiceDefault myServiceDefault;
    
        public boolean checkStatus(String service) {
            service = service.toLowerCase();
    
            if (service.equals("one")) {
                return myServiceOne.checkStatus();
            } else if (service.equals("two")) {
                return myServiceTwo.checkStatus();
            } else if (service.equals("three")) {
                return myServiceThree.checkStatus();
            } else {
                return myServiceDefault.checkStatus();
            }
        }
    }
    

    This is still poorly designed because adding new MyService implementation requires MyServiceAdapter modification as well (SRP violation). But this is actually a good starting point (hint: map and Strategy pattern).

提交回复
热议问题