【发布时间】:2010-04-21 18:56:35
【问题描述】:
我想了解 stackoverflow 社区对以下三种设计模式的看法。首先是实现继承;二是接口继承;三是中间立场。我的具体问题是:哪个最好?
实现继承:
class Base {
X x() const = 0;
void UpdateX(A a) { y_ = g(a); }
Y y_;
}
class Derived: Base {
X x() const { return f(y_); }
}
接口继承:
class Base {
X x() const = 0;
void UpdateX(A a) = 0;
}
class Derived: Base {
X x() const { return x_; }
void UpdateX(A a) { x_ = f(g(a)); }
X x_;
}
中间地带:
class Base {
X x() const { return x_; }
void UpdateX(A a) = 0;
X x_;
}
class Derived: Base {
void UpdateX(A a) { x_ = f(g(a)); }
}
我知道很多人更喜欢接口继承而不是实现继承。不过后者的好处是有了指向Base的指针,x()可以内联,x_的地址可以静态计算。
【问题讨论】:
标签: design-patterns inheritance interface