建造者模式: 讲一个复杂对象的构建层与其表示层相互分离, 同样的构建过程可采用不同的表示.
创建一个人类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| var Human = function (param) { this.skill = (param && param.skill) || '保密' this.hobby = (param && param.hobby) || '保密' }
Human.prototype = { getskill: function () { return this.skill }, getHobby: function () { return this.hobby }, }
|
创建一个姓名类
1 2 3 4 5 6 7 8 9 10 11 12 13
| var Named = function (name) { var that = this ;(function (name, that) { that.wholeName = name if (name.indexOf(' ') > -1) { that.FirstName = name.slice(0, name.indexOf(' ')) that.secondName = name.slice(name.indexOf(' ')) } })(name, that) }
|
创建一个职位类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| var Work = function (work) { var that = this ;(function (work, that) { switch (work) { case 'code': that.work = '工程师' that.workDescript = '每天沉醉于编程' break case 'UI': that.work = '设计师' that.workDescript = '设计是一种艺术' break default: that.work = work that.workDescript = '暂无描述' break } })(work, that) }
Work.prototype.changeWork = function (work) { this.work = work }
Work.prototype.changeDescript = function (setence) { this.workDescript = setence }
|
创建一个对象类
1 2 3 4 5 6 7 8 9 10
| function Person(name, work) { var _person = new Human() _person.name = new Named(name) _person.work = new Work(work) return _person }
|
输出测试
1 2 3 4 5 6 7
| var person = new Person('chen lu', 'code') console.log(person.skill) console.log(person.name.FirstName) console.log(person.work.work) console.log(person.work.workDescript) person.work.changeDescript('吃饭睡觉打豆豆') console.log(person.work.workDescript)
|