在使用 Selenium WebDriver 时,我注意到其 API 及其类层次结构中的一种模式。
API 设置如下:
Interface A {
void doAStuff();
}
Interface B {
void doBStuff();
}
Interface C {
void doCStuff();
}
Class X implements A, B, C {
...
}
Class Y implements A, B, C {
...
}
Class Z implements A, B, C {
...
}
实现如下所示:
public void doStuffWithImplementationsOfA(A a) {
a.doAStuff();
B b = (B) a;
b.doBStuff();
C c = (C) a;
c.doCStuff();
}
public static void main(String[] args) {
A a = new X();
doStuffWithImplementationsOfA(a);
}
正如您所看到的,接口(interface) A、B 和 C 根本没有相互扩展,但在 API 中,A 的所有实现也实现了 B 和 C,从而允许交叉转换。具体来说,在 Selenium 中,WebDriver 的所有实现(如 FirefoxDriver 和 ChromeDriver)还实现了其他几个常见的不相关的接口(interface)(HasInputDevices、JavascriptExecutor 等);同样,WebElement 的所有实现都实现其他常见的不相关接口(interface)(如 Locatable)。这不仅允许而且需要接口(interface)之间的交叉转换以访问每个实现中的各种方法。
我的问题,分为三个部分:
- 这种层次结构是否符合设计模式?
- 如果有,它有名字吗?
- 以这种方式设计 API(与仅让 C 扩展 B、B 扩展 A 相比)有何优点/缺点?
编辑:这是 WebDriver API 层次结构的图表(并非详尽)。
最佳答案
这不是一个新事物 - 它是 Java 中的常见机制。看看Iterable
、Comparable
、Serialized
。许多类将实现其中的一个或多个并且工作正常。
最近,随着泛型的出现,您可以使用这样的东西,这更有意义并且不需要可怕的转换:
interface A {
void doAStuff();
}
interface B {
void doBStuff();
}
interface C {
void doCStuff();
}
public static <T extends A & B & C> void doStuff (T to) {
to.doAStuff();
to.doBStuff();
to.doCStuff();
}
这种层次结构是否符合设计模式?
据我所知,没有。
如果有,它有名字吗?
参见 1。
以这种方式设计 API(与仅让 C 扩展 B、B 扩展 A 相比)有何优点/缺点?
如果接口(interface)不是层次结构,那么就没有理由让它们如此。请参阅上面的
Iterable
和Comparable
。
关于java - 涉及交叉类型转换的设计模式的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20525258/