组合优于继承 是一个广泛引用的设计原则 — 倾向于通过 组合行为 (组合) 而不是从基类继承 (继承) 来构建对象。继承存在重大缺陷,而组合可以避免这些缺陷,尽管两者都有各自的用途。
继承与组合
INHERITANCE → a class EXTENDS another, inheriting its behavior ("IS-A" relationship):
class Dog extends Animal
COMPOSITION → a class is BUILT FROM other objects/behaviors ("HAS-A" / uses):
class Car { constructor() { this.engine = new Engine(); } } // composes behaviors
→ composition: combine smaller pieces; inheritance: derive from a parent
为什么继承存在问题
✗ TIGHT COUPLING → subclasses are tightly bound to their parent's implementation (changes
to the parent can break subclasses — the "fragile base class" problem)
✗ RIGID hierarchies → deep/wide inheritance trees become hard to change and understand
✗ Inflexible → a class can usually only inherit from ONE parent; behavior is fixed at compile
time; hard to combine behaviors from multiple sources
✗ Forces an "IS-A" relationship that may not truly hold; exposes parent internals
