介绍
※ 用于把抽象化与实现化解耦
※ 使得二者可以独立变化
※ (未找到JS中的经典应用)
实现代码
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()
设计原则验证
● 抽象和现实分离,解耦
● 符合开放封闭原则