抽象和实现分离,解耦,使得二者可以独立变化。
比如:这里有各种颜色的图形
可以把四个图形分别画出来,
但是这会让画图形和添加颜色混在一块儿了。我们可以分开:
代码:
//保留颜色
class Color {
constructor(name) {
this.name = name;
}
}
class Shape {
constructor(name, color) {
this.name = name;
this.color = color;
}
draw() {
console.log(`${this.color.name} ${this.name}`);
}
}
let red = new Color('red');
let yellow = new Color('yellow');
let circle = new Shape('circle', red);
circle.draw();
let triangle = new Shape('triangle', yellow);
triangle.draw();
// red circle
// yellow triangle
来源:CSDN
作者:HappyChen666
链接:https://blog.csdn.net/u013565133/article/details/103616035