Composition over inheritance
Composition over inheritance
Definition
Composition over inheritance: is the principle that classes should achieve polymorphic behavior and code reuse by their composition rather than inheritance from a base or parent class.
Composition : containing instances of other classes that implement the desired functionality
mixin: a class that contains methods for use by other classes without having to be the parent class of those other classes. Mixins are sometimes described as being “included” rather than “inherited”.
Why
- To favor composition over inheritance is a design principle that gives the design higher flexibility
- Composition also provides a more stable business domain in the long term as it is less prone to the quirks of the family members
Drawbacks
- methods being provided by individual components may have to be implemented in the derived type, even if they are only forwarding methods
Avoiding Drawbacks
This drawback can be avoided by using traits, mixins, (type) embedding, or protocol extensions.
Some languages provide specific means to mitigate this:
- Raku provides a
handles
keyword to facilitate method forwarding. - Java provides Project Lombok[5] which allows delegation to be implemented using a single @Delegate annotation on the field, instead of copying and maintaining the names and types of all the methods from the delegated field.[6]
- Swift extensions can be used to define a default implementation of a protocol on the protocol itself, rather than within an individual type’s implementation.[7]
- Kotlin includes the delegation pattern in the language syntax.[8]
- Go type embedding avoids the need for forwarding methods.[9]
- D provides an explicit “alias this” declaration within a type can forward into it every method and member of another contained type. [10]
ref
- https://en.wikipedia.org/wiki/Composition_over_inheritance
- https://en.wikipedia.org/wiki/Mixin
- 上一篇 电脑使用手机当webcam
- 下一篇 做一個彈鋼琴的機械手