工厂类的动态行为

aku*_*001 2 java oop design-patterns

我有一个工厂类,提供一堆属性.

现在,属性可能来自数据库或属性文件.

这就是我想出来的.

public class Factory {

    private static final INSTANCE = new Factory(source);

    private Factory(DbSource source) {
        // read from db, save properties
    }

    private Factory(FileSource source) {
        // read from file, save properties
    }

    // getInstance() and getProperties() here
}
Run Code Online (Sandbox Code Playgroud)

什么是基于环境在这些行为之间切换的简洁方法.我想避免每次都重新编译该类.

bez*_*max 6

依赖注入是实现它的方法.

一般来说,在你的情况下使用依赖注入看起来像这样(例如对于Spring DI,对于Guice来说看起来会有些不同,但想法是一样的):

public interface Factory {
    Properties getProperties();
}

public class DBFactory implements Factory {
    Properties getProperties() {
        //DB implementation
    }
}

public class FileFactory implements Factory {
    Properties getProperties() {
        //File implementation
    }
}

public SomeClassUsingFactory {
    private Factory propertyFactory;

    public void setPropertyFactory(Factory propertyFactory) {
        this.propertyFactory = propertyFactory;
    }

    public void someMainMethod() {
        propertyFactory.getProperties();
    }
}

//Spring context config
<!-- create a bean of DBFactory (in spring 'memory') -->
  <bean id="dbPropertyFactory"
    class="my.package.DBFactory">
    <constructor-arg>
      <list>
        <value>Some constructor argument if needed</value>
      </list>
    </constructor-arg>
  </bean>
 <!-- create a bean of FileFactory (in spring 'memory') -->
  <bean id="filePropertyFactory"
    class="my.package.FileFactory">
    <constructor-arg>
      <list>
        <value>Some constructor argument if needed</value>
      </list>
    </constructor-arg>
  </bean>
<!-- create a bean of SomeClassUsingFactory -->
  <bean id="MainClass"
    class="my.package.SomeClassUsingFactory">
    <!-- specify which bean to give to this class -->
    <property name="propertyFactory" ref="dbPropertyFactory" />
  </bean>
Run Code Online (Sandbox Code Playgroud)

然后,在不同的环境中,您只需将xml配置文件与其他文件交换,该文件将属性设置为filePropertyFactory,然后将其传递给SomeClassUsingFactory.