The way you describe the problem, it sounds like this is a good case for using inheritance. The rule of thumb is to use inheritance if A is-a B and to use composition if A is-implemented-in-terms-of B.
The recommendation to prefer composition to inheritance does not mean "never ever use inheritance". It means use inheritance appropriately. For example, if you write a Stack class in C++ using an std::vector, you don't want to derive Stack from vector. A Stack is not a vector, it is implemented-in-terms-of a vector, which implies composition. You also want to avoid creating deep class hierarchies, because that results in tight coupling.
In your case, however, inheritance seems like an obvious choice.
发布评论
评论(1)
从您描述问题的方式来看,这听起来像是使用继承的一个很好的例子。经验法则是,如果 A 是 B,则使用继承;如果 A 是根据 B 实现的,则使用组合。
优先使用组合而不是继承的建议并不意味着“永远不要使用继承”。这意味着适当地使用继承。例如,如果您使用
std::vector
在 C++ 中编写Stack
类,则您不希望从Stack
派生>矢量。Stack
不是一个向量
,它是用向量
实现的,这意味着组合。您还希望避免创建深层类层次结构,因为这会导致紧密耦合。然而,就您而言,继承似乎是一个显而易见的选择。
The way you describe the problem, it sounds like this is a good case for using inheritance. The rule of thumb is to use inheritance if A is-a B and to use composition if A is-implemented-in-terms-of B.
The recommendation to prefer composition to inheritance does not mean "never ever use inheritance". It means use inheritance appropriately. For example, if you write a
Stack
class in C++ using anstd::vector
, you don't want to deriveStack
fromvector
. AStack
is not avector
, it is implemented-in-terms-of avector
, which implies composition. You also want to avoid creating deep class hierarchies, because that results in tight coupling.In your case, however, inheritance seems like an obvious choice.