工廠返回的可以是一個具體的對象,比如造一輛車,可以返回一個自行車對象,或者汽車對象。
但是在Spring 中需要工廠返回一個具體的Service,這就是一個抽象工廠了
一種方法是反射,個人覺得這種方式不好;
還有一種方法是巧妙的使用Map對象,工廠的一個優點就是可擴展,對於這種方式可以說是體現的淋漓盡致了,可以定義多個map,map里也可以擴充
假設現在有一個接口類:BingService
以及實現了這個接口的兩個實現類: OneBingServiceImpl,TwoBingServiceImpl
1、在工廠類里定義Map
import java.util.Map; public class BingServiceFactory { //Map中的Value是 ServiceBean private Map<String, BingService> serviceMap; //返回對應的 Service public BingService getBingService(String platform) { return serviceMap.get(platform); } public Map<String, BingService> getServiceMap() { return serviceMap; } public void setServiceMap(Map<String, BingService> serviceMap) { this.serviceMap = serviceMap; } }
2、是用注解方式,配置工廠,同時使用set 注入的方法,給用到工廠的bean來set一下
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import javax.annotation.Resource; import java.util.HashMap; import java.util.Map; @Configuration public class BingConfiguration { @Resource private OneServiceImpl oneService; @Resource private TwoServiceImpl twoService; @Resource private TestServiceImpl testService; @Bean public BingServiceFactory createFactory() { BingServiceFactory factory = new BingServiceFactory(); Map<String, BingService> serviceMap = new HashMap<>(); serviceMap.put("One",oneService); serviceMap.put("Two",twoService); factory.setServiceMap(serviceMap); testService.setFactory(factory); return factory; } }
@Bean 注解如果無效的話,可能得 @Bean("xxxxServiceFactory") 這樣的
3、使用set 注入的方方式來獲取工廠(當然也可以使用Autowired 注解注入)
import org.springframework.stereotype.Component; @Component public class TestServiceImpl { private BingServiceFactory factory; public void test() { BingService service = factory.getBingService("One"); } public BingServiceFactory getFactory() { return factory; } public void setFactory(BingServiceFactory factory) { this.factory = factory; } }
這個工廠可以優化的,不要Factory 這個類,直接使用Map 就行
原創文章,歡迎轉載,轉載請注明出處!