课程: Advanced Design Patterns: Design Principles

免费学习该课程!

今天就开通帐号,24,700 门业界名师课程任您挑!

Favor composition over inheritance

Favor composition over inheritance

- [Instructor] Inheritance is main state of object orient design and programming. Within inheritance, we can avoid code duplication by inheriting behaviors. This a powerful technique. But it's a technique that can easily be overused. It's also a technique that can lead to designs that are far too rigged and not extensible. Our next design principle give us fore warning of this. Favor composition over inheritance. Or, as it's also known, HAS-A is better than IS-A. So remember, IS-A is an inheritance relationship. A dog is an animal. Or say, a taxi is an automobile. HAS-A is a relationship of composition. A dog has a owner. A taxi has a passenger. Composition can provide an alternative sub classing for extending behavior, and a powerful one. Let's look at an example. Consider a coffee shop that sells coffee. They have a simple class that represents their coffee. And they have a cost method and a prepare…

内容