我有一个提供一系列属性的工厂类。
现在,属性可能来自数据库,也可能来自属性文件。
这就是我想出来的。
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
}基于环境在这些行为之间切换的干净方法是什么?我想避免每次都要重新编译这个类。
发布于 2010-06-18 14:47:50
依赖注入就是这样做的。
DI: DI
通常,在您的情况下使用依赖注入将如下所示(示例用于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>然后,在不同的环境中,您只需将xml配置文件与其他将属性设置为filePropertyFactory的文件交换,并将其传递给SomeClassUsingFactory。
发布于 2010-06-18 15:12:59
简单地说,不要使用单例。
“从上面参数化。”在代码中有意义的地方构建所需的实现。在构造实例时,将实例向下传递给需要它的对象。
发布于 2010-06-18 14:38:53
您可以定义如下内容:
public abstract Factory {
// define all factory methods here
public static Factory getFactory(FactoryType type, Object source) {
if (type == FactoryType.DB) {
return new DbFactory(source);
}
if (type == FactoryType.PROPERTIES) {
return new PropertiesFactory(source);
}
}
}
public DbFactory implements AbstractFactory { .. }
public PropertiesFactory implements AbstractFactory { .. }实例化您可以使用instanceof而不是您希望工厂成为单一实例的enum
new)替换为静态方法https://stackoverflow.com/questions/3067630
复制相似问题