组合模式

  • 组合模式:作用于将多个部分通过组合变成一个整体
  • 比如:我们去麦当劳点了一个汉堡、两个薯条和一杯可乐。我们可以把这些东西看传一个个部分或者说组件,通过组合就可以将整个套餐产出给顾客。这个就是组合模式
  • 举个例子:我们在工作中经常会制作一些表单,比如登录、注册呀,或者一些信息填写等等,这些表单其实都是类似的,如果你今天制作了一个注册表单,明天做个调查文件的表单,是不是你会觉得很麻烦,有点重复劳动了。组合模式就可以解决这个问题 ```javascript window.onload = function() { // 组合寄生式继承 function inheritPrototype(subClass, superClass) { function F(){} F.prototype = superClass.prototype; subClass.prototype = new F(); subClass.prototype.constructor = subClass; }

// 基类 function Container() { this.children = []; this.element = null; }

Container.prototype = { init: function() { throw new Error(“请重写init方法”) }, add: function(child) { this.children.push(child); this.element.appendChild(child.element); return this; } }

// 基于容器基类创建表单容器 function CreateForm(id, method, action, parent) { Container.call(this); this.id = id || ‘’; this.method = method || ‘get’; this.action = action || ‘’; this.parent = parent; this.init(); }

inheritPrototype(CreateForm, Container);

CreateForm.prototype.init = function() { this.element = document.createElement(‘form’); this.element.id = this.id; this.element.method = this.method; this.element.action = this.action; }

CreateForm.prototype.show = function() { this.parent.appendChild(this.element); }

// 行容器组件 function CreateLine() { Container.call(this); this.className = this.className === undefined ? ‘form-line’: ‘form-line ‘ + className; this.init(); }

inheritPrototype(CreateLine, Container);

CreateLine.prototype.init = function() { this.element = document.createElement(‘div’); this.element.className = this.className; }

// label function CreateLabel(text, forName) { this.text = text || ‘’; this.forName = forName || ‘’; this.init(); }

CreateLabel.prototype.init = function() { this.element = document.createElement(‘label’); this.element.setAttribute(‘for’, this.forName); this.element.innerText = this.text; }

// input function CreateInput(type, id, name, defaultValue) { this.type = type || ‘’; this.id = id || ‘’; this.name = name || ‘’; this.defaultValue = defaultValue || ‘’; this.init(); }

CreateInput.prototype.init = function() { this.element = document.createElement(‘input’); this.element.type = this.type; this.element.id = this.id; this.element.name = this.name; this.element.value = this.defaultValue;
}

// 开始使用 var form = new CreateForm(‘owner-form’, ‘get’, ‘/aaa.html’, document.body);

var userLine = new CreateLine() .add(new CreateLabel(‘用户名’, ‘user’)) .add(new CreateInput(‘text’, ‘user’, ‘user’)); var pwdLine = new CreateLine() .add(new CreateLabel(‘密码’, ‘pwd’)) .add(new CreateInput(‘password’, ‘pwd’, ‘pwd’)); var submitLine = new CreateLine() .add(new CreateInput(‘submit’, ‘’, ‘’, ‘登录’));

form.add(userLine).add(pwdLine).add(submitLine).show(); } ```