[设计模式][组合模式][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
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞