通过实例工厂方法创建多态Bean

时间:2013-10-03 07:40:01

标签: java spring polymorphism factory-method

当我通过实例工厂方法创建bean时,我可以在xml中为“factory-method”指定一个参数吗?例如在下面的代码片段中,我可以指定我的工厂方法createAdapter()接受一个参数,该参数确定实例化的bean的确切类型。

createAdapter() - >
<bean id="myFactoryBean" class="..." abstract="true">
...
</bean>
<!-- The bean to be created via the factory bean -->
<bean id="exampleBean"
factory-bean="myFactoryBean"
factory-method="createAdapter"/>

我在这里有几个问题:

1)myFactoryBean可以是一个抽象类吗?同时,它有一个createAdapter方法,它根据不同的输入参数返回不同的bean?

2)工厂方法createAdapter的输入,我只能在运行时知道,我不知道什么时候我试图在sprint配置中指定。

基本上,我有以下代码库,我想将其转换为spring bean,我不知道如何:

//abstract and factory class
public abstract class QueryAdapter
{
   public static queryAdapter createAdapter(Query query) {
       if (query instanceof QueryByCustomer) {
           return new QueryByCustomerAdapter((QueryByCustomer)query);
       } else if (query instanceOf QueryByDevice) {
           return new QueryByDeviceAdapter((QueryByDevice)query);
       }
   }
   public abstract QueryResult query();
   //some other shared methods
}

//inheritated class 1
public class QueryByCustomerAdapter extends QueryAdapter
{
    public QueryByCustomerAdapter(QueryByCustomer queryByCustomer) {

    }

    @Override
    public QueryResult query() {
    }
}

//inheritated class 2
public class QueryByDeviceAdapter extends QueryAdapter
{
        public QueryByDeviceAdapter(QueryByDevice queryByDevice) {

}

@Override
public QueryResult query() {
    }
}

0 个答案:

没有答案