【策略模式】如何結合spring實現一個介面多個實現,如何解決介面選擇問題
阿新 • • 發佈:2018-12-09
1、首先把對映關係放在spring-mvc.xml配置檔案
<bean id="dispatcher" class="com.ms.kai.bms.dispatcher.AbstractDispatcherImpl"> <property name="serviceMap"> <map> <entry key="10001" value-ref="serviceAImpl"/> <entry key="10002" value-ref="serviceBImpl"/> <entry key="10003" value-ref="serviceCImpl"/> </map> </property> </bean>
2、程式碼實現
@Service("dispatcher") public class AbstractDispatcherImpl { private Map<Integer, Iservice> serviceMap = new HashMap<Integer, Iservice>(); @Override public RestoreDto dispatcherDraw(String key) { Iservice service = getServiceMap.get("10001"); return service.query(); } public Map<Integer, Iservice> getServiceMap() { return serviceMap; } public void setServiceMap(Map<Integer, Iservice> serviceMap) { this.serviceMap = serviceMap; } }
public interface Iservice
{
public void query();
}
@Component("serviceAImpl")
public class ServiceAImpl implements Iservice
{
@Override
public void query(){
}
}
@Component("serviceBImpl")
public class ServiceBImpl implements Iservice
{
@Override
public void query(){
}
}