假设具有以下层次结构的类库的一部分:
class Super {
void doSomething() {
System.out.println("Super is doing something");
}
}
class SubOne extends Super {
@Override
void doSomething() {
System.out.println("SubOne is doing something");
}
void doSomethingElse() {
System.out.println("SubOne is doing something else");
}
}
class SubTwo extends Super {
@Override
void doSomething() {
System.out.println("SubTwo is doing something");
}
void doSomethingDifferent() {
System.out.println("SubTwo is doing something different");
}
}
现在有人定义了一个新的界面,提供与SubOne和SubTwo类相关的行为:
interface NewBehavior {
void doSomethingNew();
}
据我所知,如果我们无法修改Super,SubOne和SubTwo的源代码,有两种方法可以定义实现NewBehavior的SubOne和SubTwo的新版本。
一个是在Super的子类中实现NewBehavior,然后通过继承新版本的Super(并可能包装SubOne和SubTwo对象)来创建新版本的SubOne和SubTwo:
class ExtendingSuperNewBehavior extends Super
implements NewBehavior {
@Override
public void doSomethingNew() {
System.out.println("ExtendingSuperNewBehavior is doing something new");
}
}
class ExtendingSuperSubOneNewBehavior extends ExtendingSuperNewBehavior {
// Here we need to either wrap SubOne or redefine doSomethingElse()
// with the same implementation.
// SubOne mSubOne = new SubOne();
// void doSomethingElse() {
// mSubOne.doSomethingElse();
// }
void doSomethingElse() {
System.out.println("SubOne is doing something else");
}
}
class ExtendingSuperSubTwoNewBehavior extends ExtendingSuperNewBehavior {
// Here we need to either wrap SubTwo or redefine doSomethingDifferent()
// with the same implementation.
// SubTwo mSubTwo = new SubTwo();
// void doSomethingDifferent() {
// mSubTwo.doSomethingDifferent();
// }
void doSomethingDifferent() {
System.out.println("SubTwo is doing something different");
}
}
另一种是定义一个实现NewBehavior的类,并在每个新版本的SubOne和SubTwo中包装一个实例:
class NewBehaviorImpl implements NewBehavior {
@Override
public void doSomethingNew() {
System.out.println("NewBehaviorImpl is doing something new");
}
}
class ImplementingSubOne extends SubOne
implements NewBehavior {
NewBehavior mNewBehavior = new NewBehaviorImpl();
public void doSomethingNew() {
mNewBehavior.doSomethingNew();
}
}
class ImplementingSubTwo extends SubTwo
implements NewBehavior {
NewBehavior mNewBehavior = new NewBehaviorImpl();
public void doSomethingNew() {
mNewBehavior.doSomethingNew();
}
}
显然,这两种方法都有效,但是如果SubOne和/或SubTwo公开了一个大型接口(通常是库类),无论选择哪种方法,都会有很多方法转发。
有人能想到一种方法来重用相同的接口实现来避免代码转发吗?这会有很大的帮助。
答案 0 :(得分:0)
考虑使用像AspectJ这样的AOP(面向方面编程)库。您可以使用AOP执行的操作之一是向现有类引入其他属性或方法。在您的示例中,您将透明地将新方法添加到SubOne和SubTwo子类,而无需触及这些类。 AOP应用程序基本上将以透明的方式使用原始类的代理。