| 继承适合 | is-a 语义稳定、契约可完整继承 |
|---|---|
| 组合适合 | 行为可插拔、复用为主 |
| 手段 | 委托 + 接口,必要时用策略模式 |
对照
对照
// 继承:StrongExporter extends Compressor —— 压缩实现被绑死
// 组合:
class Exporter {
private final Compressor compressor;
Exporter(Compressor c) { this.compressor = c; }
}优先用组合与委托获得复用:继承把子类绑死在父类实现与接口上,组合可以运行期替换、只暴露需要的能力,是 GoF 在《设计模式》中给出的核心取向。
| 继承适合 | is-a 语义稳定、契约可完整继承 |
|---|---|
| 组合适合 | 行为可插拔、复用为主 |
| 手段 | 委托 + 接口,必要时用策略模式 |
// 继承:StrongExporter extends Compressor —— 压缩实现被绑死
// 组合:
class Exporter {
private final Compressor compressor;
Exporter(Compressor c) { this.compressor = c; }
}