Skip to content

Latest commit

 

History

History
71 lines (59 loc) · 1.73 KB

File metadata and controls

71 lines (59 loc) · 1.73 KB

五. 桥接模式

在系统沿着多个维度变化的时候,不增加起复杂度已达到解耦的目的

场景

在我们日常开发中,需要对相同的逻辑做抽象的处理。桥接模式就是为了解决这类的需求。

桥接模式最主要的特点就是将实现层和抽象层解耦分离,是两部分可以独立变化

比如我们写一个跑步游戏,对于游戏中的人和精灵都是动作单元。而他们的动作也是非常的统一。比如人和精灵和球运动都是 x,y 坐标的改变,球的颜色和精灵的颜色绘制方式也非常的类似。 我们就可以将这些方法给抽象出来。

//运动单元
function Speed(x, y) {
  this.x = x;
  this.y = y;
}
Speed.prototype.run = function() {
  console.log('动起来');
};
// 着色单元
function Color(cl) {
  this.color = cl;
}
Color.prototype.draw = function() {
  console.log('绘制色彩');
};

// 变形单元
function Shape(ap) {
  this.shape = ap;
}
Shape.prototype.change = function() {
  console.log('改变形状');
};
//说话单元
function Speak(wd) {
  this.word = wd;
}
Speak.prototype.say = function() {
  console.log('请开始你的表演');
};

//创建球类,并且它可以运动可以着色
function Ball(x, y, c) {
  this.speed = new Speed(x, y);
  this.color = new Color(c);
}
Ball.prototype.init = function() {
  //实现运动和着色
  this.speed.run();
  this.color.draw();
};

function People(x, y, f) {
  this.speed = new Speed(x, y);
  this.speak = new Speak(f);
}

People.prototype.init = function() {
  this.speed.run();
  this.speak.say();
};
//...

//当我们实例化一个人物对象的时候,他就可以有对应的方法实现了

var p = new People(10, 12, '我是一个人');
p.init();