设计模式js篇--组合模式

2019-03-26  本文已影响0人  我追求的小世界
一、定义

将对象组合成树形结构以表示“部分-整体”的层次结构,组合模式使得用户对单个对象和组合对象的使用具有一致性。
角色:
(1)子对象
(2)组合对象
(3)抽象类:主要定义了参与组合的对象的公共接口,也可以直接在组合对象中定义

二、举例

eg1: github上面原有的例子(https://github.com/sohamkamani/javascript-design-patterns-for-humans#-bridge)。
场景说明:组织里面有各种员工,可以进行添加,不同的员工有不同的姓名、工资等。

// 场景 以员工为例。这里我们有不同的员工类型
// 开发者
class Developer {
    constructor(name, salary) {
        this.name = name
        this.salary = salary
    }
    getName() {
        return this.name
    }
    setSalary(salary) {
        this.salary = salary
    }
    getSalary() {
        return this.salary
    }
    getRoles() {
        return this.roles
    }
    develop() {
        /* */
    }
}
// 设计师
class Designer {
    constructor(name, salary) {
        this.name = name
        this.salary = salary
    }
    getName() {
        return this.name
    }
    setSalary(salary) {
        this.salary = salary
    }
    getSalary() {
        return this.salary
    }
    getRoles() {
        return this.roles
    }
    design() {
        /* */
    }
}
// 一个由几种不同类型的员工组成的组织
class Organization {
    constructor(){
        this.employees = []
    }
    // 追加元素
    addEmployee(employee) {
        this.employees.push(employee)
    }
    //  叶对象都有一样的getSalary方法。在根对象执行的时候,可以使用leaf.execute的模式来调用对象的方法。
    getNetSalaries() {
        let netSalary = 0
        this.employees.forEach(employee => {
            netSalary += employee.getSalary()
        })
        return netSalary
    }
}
// 调用
// Prepare the employees
const john = new Developer('John Doe', 12000)
const jane = new Designer('Jane', 10000)
// Add them to organization 优势:无论多少员工类型 对整个组合对象只调用一次
const organization = new Organization()
organization.addEmployee(john)
organization.addEmployee(jane)
console.log("Net salaries: " , organization.getNetSalaries()) // Net Salaries: 22000

eg2:表单校验
场景:创建一个表单.要求点提交按钮,可以保存和验证各项的值.这个表单的元素有多少项并不知道,也不知道具体是什么内容,是注册表单验证还是登陆表单验证?根据用户的需求而异,也就是实现一个动态表单


image.png
var CompositeForm = function(id) {
  this.formComponents = [];
  this.formElement = document.createElement('form');
  this.formElement.id = id;
  this.formElement.onsubmit = function() {
    return false;
  }
}

CompositeForm.prototype.add = function(child) {
  this.formComponents.push(child);
}

CompositeForm.prototype.loadElements = function() {
  for(var i=0; i<this.formComponents.length; i++) {
    this.formElement.appendChild(this.formComponents[i].divElement);
  }
  var submitButton = document.createElement('input');
  submitButton.id = 'sub';
  submitButton.type = 'submit';
  this.formElement.appendChild(submitButton);
}

CompositeForm.prototype.save = function() {
  for(var i=0; i<this.formComponents.length; i++) {
    this.formComponents[i].save();
  }
}

var InputField = function(label, id, type) {
  //创建input节点
  this.input = document.createElement('input');
  this.input.id = id;
  this.input.type = type;
  //创建文本节点
  this.label = document.createElement('label');
  var labelTextNode = document.createTextNode(label);
  this.label.appendChild(labelTextNode);
  //创建div节点
  this.divElement = document.createElement('div');
  this.divElement.className = 'input-field';
  this.divElement.appendChild(this.label);
  this.divElement.appendChild(this.input);
}

InputField.prototype.save = function() {
  var value = this.input.value;
  sessionStorage.setItem(this.input.id, value);
  console.log(sessionStorage.getItem(this.input.id));
}

var form = new CompositeForm('myform');
//开始组合
form.add(new InputField('用户名', 'userName', 'text'));
form.add(new InputField('密码', 'password', 'password'));
form.add(new InputField('邮箱', 'email', 'text'));

//装填所有节点
form.loadElements();

//append到body
document.body.appendChild(form.formElement);

//试验一下
document.getElementById('sub').onclick = function() {
  form.save();
}


// 目前项目中类似的 校验是否必填
// 校验方法
 checkByValidator (func, value, message) {
    if (!func(value)) {
      return false
    }
    return true
  },
// 组合校验
checkEmptyRules (obj, rules) {
    let isEmpty = false
    for (let item of rules) {
      if (((!obj[item.name] && obj[item.name] !== 0) || 
      (obj[item.name] instanceof Array && !obj[item.name].length) ) || 
      (item.type && this.checkByValidator(this.$validator[item.type], this.create.mobileNo))) {
          Message.error(item.message)
          isEmpty = true
          break
      }
    }
    return isEmpty
  },
// 调用
 createRules: [
        { name: 'userId', message: '手机号码必传',type:'phone' },
        { name: 'enterpriseName', message: '邮箱必传',type:'email' },
        { name: 'certificateType', message: '证件类型必传',type:'number' },    
  ]

  if (this.$utils.checkEmptyRules(this.create, this.createRules)) {
       return
  }
三、总结

使用场景:
A.含有某种层级结构的对象集合(具体结构在开发过程中无法确定)
B.希望对这些对象或者其中的某些对象执行某种操作

缺点:
因为组合对象的任何操作都会对所有的子对象调用同样的操作,所以当组合的结构很大时会有性能问题。

上一篇 下一篇

猜你喜欢

热点阅读