橋接模式

  • 將抽象部分與他的實現部分分離,這樣抽象化與實現化解耦,使他們可以獨立的變化
  • 應用場景:實現系統可能有多個角度分類,每一種角度都可能變化
  • 橋接雙方可以通過實現橋接口進行單方面擴展,也可以繼續抽象類而單方面擴展,而之間的調用就從橋接口來作爲突破口,不會受到雙方擴展的任何影響
class A{
  constructor(bridge){
    this.bridge = bridge;
  }
  go(){
    console.log(`從${this.from()}到${this.bridge.to()}`);
  }
  from(){
    throw new Error('子類必須實現此方法')
  }
}
class A1 extends A{
  from(){return 'A1'}
}
class A2 extends A{
  from(){return 'A2'}
}
class B{
  to(){
    throw new Error('子類必須實現此方法')
  }
}
class B1 extends B{
  from(){return 'B1'}
}
class B2 extends B{
  from(){return 'B2'}
}
let b2 = new B2();
let a1 = new A1(b2);
a1.go();

應用場景

//繪製一個小球 將定位和繪製顏色分開,利用Circle作爲橋,傳遞數據
function Position(x,y){
  this.x = x;
  this.y = y;
}
function CircleColor(color){
  this.color = color;
}
function Circle(x,y,circleColor){
  this.position = new Position(x,y);
  this.circleColor = new CircleColor(circleColor);
}
Circle.prototype.render=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.circleColor.color;
  ctx.fill();
}
let c = new Circle(100,100,'red');
c.render();

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章