桥接模式
特点
介绍
- 桥接模式将继承关系转化成关联关系,它降低了类与类之间的耦合度,减少了系统中类的数量,也减少了代码量。
demo
更多详细代码
function Color(color) {
if (!color || typeof color !== "string") {
throw new Error("need color!");
}
this.color = color;
}
Color.prototype.getColor = function () {
return this.color;
};
function Shape(shape, color) {
if (!shape || typeof shape !== "string") {
throw new Error("need shape!");
}
this.shape = shape;
}
Shape.prototype.setColor = function(color){
if (!color || Color.isPrototypeOf(color)) {
throw new Error("need color prototype Color!");
}
this.color = color;
}
Shape.prototype.draw = function () {
console.log(`${this.shape} - ${this.color.getColor()}`);
};
const red = new Color("red");
const blue = new Coloe("blue");
const redCircle = new Shape("circle");
redCircle.setColoe(red);
redCircle.draw(); // circle-red;
redCircle.setColoe(blue);
redCircle.draw(); // circle-blue;