Inheritance 如何为基类和派生类编写包装器(适配器)?
我有两个类,Base和Derived,我想围绕它们编写包装器。派生包含基础中不存在的其他功能。这些类不在我的控制范围内,我无法修改它们 问题是:如何包装这两个类而不必a)强制转换或b)大量代码重复 以下是一个铸造解决方案:Inheritance 如何为基类和派生类编写包装器(适配器)?,inheritance,design-patterns,wrapper,adapter,Inheritance,Design Patterns,Wrapper,Adapter,我有两个类,Base和Derived,我想围绕它们编写包装器。派生包含基础中不存在的其他功能。这些类不在我的控制范围内,我无法修改它们 问题是:如何包装这两个类而不必a)强制转换或b)大量代码重复 以下是一个铸造解决方案: class BaseWrapper { Base b; someFunction() { b.someFunction(); } } class DerivedWrapper : BaseWrapper { someOther
class BaseWrapper {
Base b;
someFunction() {
b.someFunction();
}
}
class DerivedWrapper : BaseWrapper {
someOtherFunction() {
((Derived) b).someOtherFunction();
}
}
这里有一个是重复的:
class BaseWrapper {
Base b;
someFunction() {
b.someFunction();
}
}
class DerivedWrapper {
Derived d;
someFunction() {
d.someFunction();
}
someOtherFunction() {
d.someOtherFunction();
}
}
与第二种解决方案相比,我更喜欢第一种解决方案,但肯定有更好的解决方案……(注意:假设此代码是C,或类似C的伪代码)
我能想到的几乎是将BaseWrapper子类化,将对对象的附加引用作为其实际类型(派生),并将b设置为(Base)d
。假设您在构造函数中传递包装对象,我会将其设置为:
class BaseWrapper {
Base b;
someFunction() {
b.someFunction();
}
}
class DerivedWrapper : BaseWrapper {
Derived d;
DerivedWrapper(Derived d) {
this.d = d;
this.b = (Base) d;
}
someOtherFunction() {
d.someOtherFunction();
}
}
someFunction
继续从超类工作,因为您仍然有一个Base b
。您仍然有一个强制转换,但它在构造函数中,不必在每个方法中都指定
(注意:您甚至不需要构造函数中的强制转换,但它很好地提醒您,您的其他引用不是同一类型。)我喜欢您的答案,但我有点恼火,因为我没有立即想到它。:)我怀疑还有更好的办法。你甚至不需要构造函数中的强制转换,这是真的。尽管如此,我还是喜欢显式转换而不是隐式转换。我会在回答中记下的。