Inheritance vs Composition

上一篇 / 下一篇  2014-09-02 11:53:24 / 个人分类:Java

From http://www.artima.com/designtechniques/compoinh5.html


a few guidelines that reflect how I tend to select between composition and inheritance.

Make sure inheritance models the is-a relationship
My main guiding philosophy is that inheritance should be used only when a subclass is-a superclass. In the example above, an Apple likely is-a Fruit, so I would be inclined to use inheritance.

An important question to ask yourself when you think you have an is-a relationship is whether that is-a relationship will be constant throughout the lifetime of the application and, with luck, the lifecycle of the code. For example, you might think that an Employee is-a Person, when really Employee represents a role that a Person plays part of the time. What if the person becomes unemployed? What if the person is both an Employee and a Supervisor? Such impermanent is-a relationships should usually be modelled with composition.

Don't use inheritance just to get code reuse
If all you really want is to reuse code and there is no is-a relationship in sight, use composition.

Don't use inheritance just to get at polymorphism
If all you really want is polymorphism, but there is no natural is-a relationship, use composition with interfaces. I'll be talking about this subject next month.


TAG:

 

评分:0

我来说两句

日历

« 2024-03-29  
     12
3456789
10111213141516
17181920212223
24252627282930
31      

数据统计

  • 访问量: 10451
  • 日志数: 15
  • 书签数: 1
  • 建立时间: 2008-12-01
  • 更新时间: 2014-09-02

RSS订阅

Open Toolbar