目前我正在研究重构一个类,并且一直在研究设计模式,我很好奇哪种模式(如果有的话(适用于这个场景。当前类的外观:
public WebDriver window(int index) {//stuff};
public WebDriver window(String nameOrId) {//stuff};
public WebDriver windowByTitle(String title) {//title specific stuff};
public WebDriver frame(int index) {//stuff};
public WebDriver frame(String nameOrId) {//stuff};
public WebDriver frameByTitle(String title) {//title specific stuff};
public WebDriver alert(int index) {//stuff};
public WebDriver alert(String nameOrId) {//stuff};
public WebDriver alertByTitle(String title) {//title specific stuff};
现在假设这9种方法中的每一种,我都想添加一个可选的辅助参数,即Duration
,例如:
public WebDriver window(int index, Duration of) {//stuff}
但我在这些方法中的每一个方法上都需要这样的功能,不想创建9个重载方法,重复使用许多核心代码。这些方法中的每一个都创建了一个新的Wait
,它调用一个标准构造函数来创建它,假设是默认的Duration
,但我也想提供提供自己的Duration的能力。
处理这样一个问题的最佳模式是什么?我计划完全重写这门课,但我想创造一个好的、坚实的设计。
我的想法:
- 策略模式(窗口切换策略、框架切换策略、警报切换策略(
- 某种Builder,当我们只创建一个方法时,我们可以建立状态来决定是否应该将持续时间传递给新的Wait((;构造函数
窗口的伪(int索引({}:
try {
new Wait().until(windowIsReady());
} catch(TimeoutException ex) {
//ex stuff
}
我希望这里有一个可选的持续时间,如果是这样的话,我们会改为这样做,但当我们不需要调用方指定的显式持续时间时,会提供很好的可重用性:
new Wait(duration).until(windowIsReady());
等待看起来像这样:
public Wait() {}
public Wait(Duration duration) {}
感谢
我认为问题已经存在于代码中,应该首先删除。如果你使用这样的方法:
public static class Select {
final Type type;
// Only one of these should be set.
int index;
String key;
private Select(Type type) {
this.type = type;
}
private Select setIndex(int index) {
this.index = index;
return this;
}
private Select setKey(String key) {
this.key = key;
return this;
}
public static Select by(Type type, int index) {
assert (type == Index);
return new Select(type).setIndex(index);
}
public static Select by(Type type, String key) {
assert (type != Index);
return new Select(type).setKey(key);
}
enum Type {
Index,
NameOrId,
Title;
}
}
// Now only one of each.
public WebDriver window(Select select) {
}
public WebDriver frame(Select select) {
}
public WebDriver alert(Select select) {
}
private void test() {
// Easy to use.
window(Select.by(Index, 1));
window(Select.by(NameOrId, "hello"));
}
现在,您可以非常简单地添加新参数,因为现在每种类型只有一个方法,不需要添加更多来添加其他参数。