【发布时间】:2014-03-08 21:19:45
【问题描述】:
这是一个理论问题,关于面向对象的设计,我还没有想出一个直截了当的很好解释的答案。 假设我们有一个 Music Event 类,我们想实现一个 Rating 类,它可能有一个 int 成员(星号 1-5),可能还有一个 getter 和一个 setter 函数。 也许我还没有想到更大的图景?
如果我们希望我们的 Music Event 类具有评级(只是一个而不是数组),为什么最好从 Rating 类继承? ,而不是在 Music 事件类中添加 Rating 类成员?
在编码中:
//why is this better...
class MusicEvent:public Rating {
string name;
string duration;
//and other stuff here
}
//...than this
class MusicEvent {
string name;
string duration;
Rating rating;
//and other stuff here
}
【问题讨论】:
-
古老的格言说“更喜欢组合而不是继承”。
标签: java c++ oop design-patterns inheritance