[设想形式][组合形式][Javascript]

The Composite Pattern is a partitioning design pattern. The composite pattern describes that a group of objects is to be treated in the same way as a single instance of object. The intent of a composite is to “compose” objects into tree structures to represent part-whole hierarchies. Implementing the composite pattern lets client treat individual objects and compositions uniformly.
From http://en.wikipedia.org/wiki/Composite_pattern

定义

组合形式的目的是解耦客户顺序与庞杂元素内部架构,使得客户顺序看待一切子元素都厚此薄彼

每个子节点都能够使庞杂的存在,关于父节点来讲,不需要知道子节点的庞杂性或许完成子节点的庞杂性,只需要关注子节点的特定要领,便能够运用子节点。简化了父和子之间的关联。

关于子节点来讲也是一样的,过量的接口暴露有时候也是一种滥用,同时也减少了对外部的依靠。

需求

《[设想形式][组合形式][Javascript]》

按钮组需求:

  • 有如许一组按钮,他们横向的举行分列,依据当前用户权限设置有哪些按钮被显现
  • 按钮能够分红subgroup,按特定的功用举行分别subgroup

类图

《[设想形式][组合形式][Javascript]》

角色

  • AbstractButton (Component) 定义一组大众的接口
  • Button (Leaf) 示意恭弘=叶 恭弘子节点的对象,恭弘=叶 恭弘子节点没有本身的子节点
  • ButtonGroup (Composite) 定义有枝节点行动,用来存储子部件,在Component接口中完成与子部件有关操纵

完成

var prototype = require('prototype');

var AbstractButton = prototype.Class.create({
  render: function() {
    throw new Error('method must be override!');
  }
});

var Button = prototype.Class.create(AbstractButton, {
  initialize: function(id, group) {
    this.id = id;
    this.group = group;
  },

  render: function () {
    console.log('render: Button的ID是:'+this.id+', group是:'+this.group);
  }
});

var ButtonGroup = prototype.Class.create(AbstractButton, {
  initialize: function () {
    this.buttons = [];
  },

  add: function (btn) {
    if (btn instanceof Button) {
      this.buttons.push(btn);
    }
  },

  remove: function (id) {
    for (var i = this.buttons.length - 1; i >= 0; i--) {
      if(this.buttons[i].id === id){
        this.buttons.splice(i, 1);
      }
    }
  },

  getChild: function (id) {
    var search = [];
    for (var i = this.buttons.length - 1; i >= 0; i--) {
      if(this.buttons[i].id === id){
        search.push(this.buttons[i]);
      }
    }

    return search;
  },

  render: function () {
    for (var i = this.buttons.length - 1; i >= 0; i--) {
      this.buttons[i].render();
    }
  }
});

var Main = function () {

  var editBtn = new Button('editbtn', 'edit');
  var deleteBtn = new Button('deletebtn', 'edit');
  var manageBtn = new Button('managebtn', 'edit');

  var btngroup = new ButtonGroup();
  btngroup.add(editBtn);
  btngroup.add(deleteBtn);
  btngroup.add(manageBtn);


  btngroup.render();
}

Main();

注:继续采用了PrototypeJS供应的Class来做的,运用了Prototype.Node,关于prototype怎样运用参考Prototype Doc

参考

    原文作者:leewind
    原文地址: https://segmentfault.com/a/1190000000642045
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞