1. 桥接模式的定义
- 将抽象部分与他的实现部分分离,这样抽象化与实现化解耦,使他们可以独立的变化
- 应用场景是实现系统可能有多个角度分类,每一种角度都可能变化.
- 桥方可以通过实现桥接口进行单方面扩展,而另一方可以继承抽象类而单方面扩展,而之间的调用就从桥接口来作为突破口,不会受到双方扩展的任何影响
class A {
constructor(bridge) {
this.bridge = bridge;
}
go() {
console.log(`从${this.from()}到${this.bridge.to()}`);
}
}
class A2 extends A {
from() {
return 'A2';
}
}
class B {
to() { }
}
class B2 extends B {
to() {
return 'B2';
}
}
let b = new B2();
let a = new A2(b);
a.go();
2. 场景
2.1 分离变化
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>html</title>
<style>
* {
margin: 0;
padding: 0;
}
canvas {
border: 1px solid #000;
}
</style>
</head>
<body>
<canvas id="canvas" width="600" height="600"></canvas>
<script>
//形状 颜色 坐标
function Position(x, y) {
this.x = x;
this.y = y;
}
function Color(color) {
this.color = color;
}
function Ball(x, y, color) {
this.position = new Position(x, y);
this.color = new Color(color);
}
Ball.prototype.draw = function () {
let canvas = document.getElementById('canvas');
let ctx = canvas.getContext('2d');
ctx.beginPath();
ctx.arc(this.position.x, this.position.y, 100, 0, 2 * Math.PI);
ctx.fillStyle = this.color.color;
ctx.fill();
}
new Ball(300, 300, 'red').draw();
</script>
</body>
</html>