1. 橋接模式的定義
- 將抽象部分與他的實現(xiàn)部分分離,這樣抽象化與實現(xiàn)化解耦,使他們可以獨立的變化
- 應用場景是實現(xiàn)系統(tǒng)可能有多個角度分類,每一種角度都可能變化.
- 橋方可以通過實現(xiàn)橋接口進行單方面擴展,而另一方可以繼承抽象類而單方面擴展,而之間的調用就從橋接口來作為突破口,不會受到雙方擴展的任何影響
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>