设计模式:组合模式 职责链模式

组合模式 职责链模式

组合模式

组合模式将对象组合成树形结构,以表示“部分-整体”的层次结构。 在组合模式的树形结构中,所有的节点都类似于继承了一个抽象类一样,需要实现同样名字的一个方法。

鉴于js没有抽象类这玩意;所以这个同名方法只能约定了。假如就约定为execute好了。

var BigCommand = function () {
  this.commands = [];
}

BigCommand.prototype.add = function (command) {
  this.commands.push(command);
}

BigCommand.prototype.execute = function () {
  for (var i = 0; i < this.commands.lenth; i++) {
    var command = this.commands[i];
    command.execute();
  }
}

var bigCommand = new BigCommand();

var Command = function () { }
Command.prototype.execute = function () {
  throw new Error("需要实现execute方法")
}

上诉代码,我们可以通过BigCommand生成一个组合对象,通过Command生成一个小对象。通过bigCommand.add(command),我们将叶子对象推入组合对象;组合对象也可以推入组合对象。这样代码就分离成几个部分了。

职责链模式

职责链模式:使多个对象都有机会处理请求,从而避免请求的发送者和接受者之间的耦合关系。

既然说是链了,必然有链表的数据结构在其中。鉴于js的异步特性,并不适合用单纯的一个指针来指着下一环;用cb()是更好的选择。

var Chain = function (fn) {
  this.fn = fn
  this.next = null;
} 

Chain.prototype.setNext = function (fn) {
  return this.next = fn;
}

Chain.prototype.execute = function () {
  return this.fn.apply(this, arguments);
}

Chain.prototype.cb = function () {
  return this.next && this.next.apply(this.next, arguments);
}

最后写完发现职责链模式就是个流程控制嘛……还不如直接写流程控制……

你可能感兴趣的:(设计模式:组合模式 职责链模式)