我一直在使用委托(delegate)模式来包装由工厂在第 3 方库中创建的对象。最近,该库在基类中添加了一个 protected 方法,我的包装类不再起作用。有没有人有不借助反射(reflection)的好的解决方案?
这是在第 3 方库和他们的包中,
public class Base {
public void foo();
protected void bar(); // Newly added
}
这是我自己的包,
public class MyWrapper extends Base {
private Base delegate;
public MyWrapper(Base delegate) {
this.delegate = delegate;
}
public void foo() {
delegate.foo()
}
protected void bar() {
// Don't know what to do
}
}
编辑:我原来的帖子不清楚。这两个类在不同的包中。
回答为什么我需要授权的问题。这是 Delegation/Wrapper 模式的典型用例,我无法在此处用几行代码展示它。该库公开了 Base 类,但其工厂中的实际对象是 Base 的派生类。实际类根据配置而变化。所以我不知道委托(delegate)是什么。因此,直接继承模式在这里不起作用。
最佳答案
Access Levels
Modifier Class Package Subclass World
public Y Y Y Y
protected Y Y Y N
no modifier Y Y N N
private Y N N N
protected
也有 package
访问权限,您是否看到任何具体问题:
class Base {
public void foo(){};
protected void bar(){}; // Newly added
}
class MyWrapper {
private Base delegate;
public MyWrapper(Base delegate) {
this.delegate = delegate;
}
public void foo() {
delegate.foo();
}
protected void bar() {
// Don't know what to do
delegate.bar(); //since its in same package, it can be referenced, do you expect compile time error?
}
}
此外,在使用委托(delegate)模式时为什么包装类扩展 Base
类,我没有看到具体的需要,因为你已经有一个 Base
的实例。对我来说,它更像是一个装饰器。
关于Java:委托(delegate)模式和 protected 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16235436/