组合与继承区别
- 继承
- 关系为(is-a)例如鸟类是动物 以此建立关系
- 子类可直接访问内部实现类,导致依赖父类实现细节
- 继承关系编译时确定,无法运行时作出修改
- 高度耦合,父类修改可能影响所有子类
- 组合
- 关系为(has-a) 例如汽车有发动机
- 组合对象通内部实现对外隐藏,只通过暴露一个接口交互
- 运行时灵活,
- 仅复用需要的功能,手动控制颗粒度
组合为何大于继承
例如一个类
//继承
class Bird {
constructor(name) {
this.name = name;
}
fly() {
console.log(this.name + "飞");
}
walk() {
console.log(this.name + "走");
}
}
//鸵鸟
class Struthio extends Bird {
constructor(name) {
super(name);
}
fly() {
console.error(this.name + "不能飞");
}
}
const struthio = new Struthio("鸵鸟");
struthio.fly(); //鸵鸟不能个飞
struthio.walk(); //鸵鸟走
const bird = new Bird("普通鸟");
bird.fly(); //普通鸟飞
bird.walk(); //普通鸟走
//组合
const struthio2 = {
name: "鸵鸟",
};
const birdo2 = {
name: "普通鸟",
};
const { walk: struthio2Walk } = useAction(struthio2); //fly不导出
const { walk: birdo2Walk, fly: birdo2Fly } = useAction(birdo2);
function useAction(option) {
const walk = () => {
console.log(option.name + "走");
};
const fly = () => {
console.log(option.name + "飞");
};
return { fly, walk };
}
struthio2Walk(); //鸵鸟走
birdo2Fly(); //普通鸟飞
birdo2Walk(); //普通鸟走
- 灵活度高
- 自定义控制walk是否导出
- 低耦合
- fly方法与鸵鸟无关
- 避免冗余
- 不需要重写fly方法
由树级关系降为1层关系,大幅度降低心智负担