工厂类模式实现

来源:互联网 发布:哪些手机可以刷ubuntu 编辑:程序博客网 时间:2024/06/05 17:09

总的思想就是,根据不同类型从工厂类拿到不同实例,调用实例方法,后期不用更新工厂类实现,只用加新的实现类即可。

记住一点,new出的bean,spring是注入不进来所依赖的bean。

网上很多代码是这样的。

工厂实现类:

if(a.equals("apple)){

new apple();

}else if(a.equals("banana")){

new banana();

}


那如果后期再加一个a类型,是不是又要改这个工厂类呢,这就不是工厂模式的设计初衷了。

spring可以把<bean>注册的组件分类,可以拿到同一接口所有实现类

applicationContext.getBeansOfType(InvoiceResultSyncHandler.class);

1.工厂接口

用于根据不同类型返回实例接口

public interface InvoiceResultSyncHandlerFactory {    InvoiceResultSyncHandler getHandler(InvoiceConstants.RequestType requestType);}


2.工厂接口实现

public class InvoiceResultSyncHandlerFactoryImpl implements InvoiceResultSyncHandlerFactory, ApplicationContextAware, InitializingBean {    private Map<RequestType, InvoiceResultSyncHandler> handlerMap = new HashMap<InvoiceConstants.RequestType, InvoiceResultSyncHandler>();    private ApplicationContext                         applicationContext;    @Override    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {        this.applicationContext = applicationContext;    }    @Override    public void afterPropertiesSet() throws Exception {        Map<String, InvoiceResultSyncHandler> allHandlers = applicationContext.getBeansOfType(InvoiceResultSyncHandler.class);        for (InvoiceResultSyncHandler handler : allHandlers.values()) {            handlerMap.put(handler.getRequestType(), handler);        }    }    @Override    public InvoiceResultSyncHandler getHandler(RequestType requestType) {        return handlerMap.get(requestType);    }}

3.实例接口

public interface InvoiceResultSyncHandler {    void syncResult(SyncResultRequestDto request, InvoiceDo invoiceDo);    InvoiceConstants.RequestType getRequestType();}

0 0
原创粉丝点击