我有一个基于少数条件创建的对象,例如 -
if (objType.equals("one-type")) {
targetTableName = "one_type_table";
sourceTableName = "one_type_parent";
unitTime = 1;
delayTime = 10;
} else if (objType.equals("two-type")) {
targetTableName = "two_type_table";
sourceTableName = "two_type_parent";
unitTime = 2;
delayTime = 20;
}
Config databaseConfig = new Config(targetTableName, sourceTableName, unitTime, delayTime);
我被告知我的模块必须从这种怪物中保存下来,而可以拯救我的模式是工厂。因此,我决定使用它并创建这样的界面 -
public interface ConfigInterface {
public String getSourceTable();
public String getTargetTable();
public int getDelay();
public int getUnitTime();
}
,还创建了此接口的具体实现,称为config。
然后创建一个工厂来构建此对象 -
public class ConfigFactory {
public ConfigInterface getConfig (String objType) {
if (objType.equals("one-type")) {
targetTableName = "one_type_table";
sourceTableName = "one_type_parent";
unitTime = 1;
delayTime = 10;
} else if (objType.equals("two-type")) {
targetTableName = "two_type_table";
sourceTableName = "two_type_parent";
unitTime = 2;
delayTime = 20;
}
Config databaseConfig = new Config(targetTableName, sourceTableName, unitTime, delayTime);
return databaseConfig;
}
}
现在,我只是将怪物代码转移到另一个功能中。即使很好,但是我的配置接口实际上并不是许多由工厂类生成的子类的超类。只有一种类型的配置对象,它具有所有这5个字段,这就是它。
我敢肯定,我要么使用它,要么不是解决此问题的正确解决方案。谁能告诉我怎么了,或者还有另一种神奇的模式来解决我的问题并让我寄来。
为什么不封装将这些值设置在其构造函数中的config config config config conplasses oneptype和twotype。然后将工厂更改为以下内容:
public Config getConfig (String objType) {
if (objType.equals("one-type")) {
return new OneType ();
} else if (objType.equals("two-type")) {
return new TwoType ();
}
另外,我在这种情况下将这种模式与枚举一起使用:
enum ConfigType {
one-type ("one_type_table", "one_type_parent", 1, 10),
two-type ("two-type_table", "two_type_parent", 2, 20)
;
ConfigType (String table, String parent, int unit, int delay) {
...
}
String getTable () {
return this.table;
}
....
}
现在,您可以概括出工厂代码并以静态枚举类型而不是运行时评估的字符串来工作。
public Config getConfig (ConfigType type) {
return new Config (type.getTable (),...
问题中代码的大小很小,因此任何实现都会像另一个一样有效。
如果objType
来自不同的类实例,例如TypeOne
和TypeTwo
,则可以超载getConfig()
方法,例如
public ConfigInterface getConfig(TypeOne type)
{
// Create and return the "one-type" object
}
public ConfigInterface getConfig(TypeTwo type)
{
// Create and return the "one-type" object
}
否则,尤其是在有许多不同类型的情况下,请考虑创建具有objType
所有可能值的enum
,而不是使用字符串。然后,您可以使用switch
语句,该语句比连续的字符串equals
检查更有效。