我有一个基于几个条件创建的对象,比如这个 -
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);
我被告知我的模块必须从这个怪物中拯救出来,可以拯救我的模式是Factory。所以我决定使用它并创建一个这样的界面 -
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;
}
}
现在我只是将我的怪物代码移到另一个函数中。即使这样也没问题,但我的配置界面实际上并不是工厂类生成的许多子类的超类。只有一种类型的Config对象,它拥有所有这5个字段,就是这样。
我确信我要么使用它错误,要么它不是解决此问题的正确方法。任何人都可以告诉我什么是错的,或者是否有另一种神奇的模式可以解决我的问题并让我把它发给我。
答案 0 :(得分:2)
为什么不封装在其构造函数中设置这些值的Config子类OneType和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 (),...
答案 1 :(得分:1)
问题中代码的大小很小,因此任何实现都与其他实现一样高效。
如果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
}
否则,特别是如果有许多不同类型,请考虑创建一个enum
,其中包含所有可能的值objType
,而不是使用字符串。然后,您可以使用switch
语句,该语句比连续字符串equals
检查更有效。