2

我需要根据收到的参数值创建一个复杂的配置对象。

我的输入是 2 个简单的变量和一个配置对象。2 个变量的组合和配置对象的内部将决定输出类的配置(始终是相同的类型)

使用简单的 if-else 执行此操作,它看起来像这样:

if (a == 1 && b == 1) {
//do some testing on the input object, configure and return the output object
else if (a == 2 && b == 1) {
//do some different testing on the input, configure and return the output.
}

等等。

a & b 可以保存大约 5 个不同的值,根据 a & b 的值,我将不得不测试输入对象中的不同内容。

我不确定解决这个问题的最佳方法。我的第一个想法是Command Pattern使用某种方法,例如:

public interface Command {
  public OutputConfig execute(InputConfig config);
}

并存储我潜在的 a & b 组合以Map<Pair<A,B>, Command>供查找。

我觉得我正在寻找一些工厂/命令/生成器模式,但不确定实现它的最佳方式。

提前致谢。

4

1 回答 1

0

我认为你需要Strategy Pattern. 您使用方法定义接口:

interface Configure{

public YourObject excecute(YourObject o);

}

您以各种所需的方式实现接口,并将其声明为成员字段。然后根据变量的值实例化适当的类。

如果你想保存对象,那么你也可以使用Command Pattern

更新:好的,在软件工程中通常没有绝对的真理。

随着Command Pattern您已经有一个执行某些任务的类,并且您希望将它们保存为从接口派生的类中的对象,以便以后使用它们等。我认为您的情况不需要这种方法,因为您需要只是定义为接口方法的不同功能。Strategy Pattern因此,在您的情况下,这是一种更优雅的方法。

于 2013-09-08T18:25:52.833 回答