设计模式知识连载(16)---建造者模式:
2017-12-13 20:00
369 查看
<body> <h3>设计模式知识连载(16)---建造者模式:</h3> <p> 建造者模式:将一个复杂对叙的构建层与其表示层相互分离,同样的构建过程可采用不同的表示 </p> <script type="text/javascript"> /** * 案例 */ // 创建一位人类 var Human = function (param) { // 技能 this.skill = param && param.skill || '保密' ; // this.skill = (param && param.skill) || '保密' ; // 这样表达会更好些 // 兴趣爱好 this.hobby = param && param.hobby || '保密' ; } ; // 类人原型方法 Human.prototype = { getSkill : function() { return this.skill ; }, getHobby : function() { return this.hobby ; } } ; // 实例化姓名类 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) ; } ; //实例化职位类 var Work = function(work) { var that = this ; // 构造器 // 构造函数中通过传入的职位特征来设置相应职位以及描述 (function(work, that) { switch (work) { case 'code' : that.work = '工程师' ; that.workDescript = '每天沉醉于编程' ; break ; case 'UI' : case 'UE' : that.work = '设计师' ; that.workDescript = '设计更似一种艺术' ; break ; case 'teach' : that.work = '教师' ; that.workDescript = '分享也是一种快乐' ; break ; default : that.work = work ; that.workDescript = '对不起,我们还不清楚您所选择职位的相关描述' ; } })(work, that) ; } ; // 更换期望的职位 Work.prototype.changeWork = function(work) { this.work = work ; } ; // 添加对职位的描述 Work.prototype.changeDescripte = function(setence) { this.workDescript = setence ; } ; /**** * 应聘者建造者 * 参数name : 姓名(全名) * 参数work : 期望职位 **/ var Person = function(name, work) { // 创建应聘者缓存对象 var _person = new Human() ; // 创建应聘者姓名解析对象 _person.name = new Named(name) ; // 创建应聘者期望职位 _person.work = new Work(work) ; // 将创建的应聘者对象返回 return _person ; } ; var person = new Person('xiao ming', 'code') ; console.log('person:', person) ; console.log('person.skill:', person.skill) ; console.log('person.name.FirstName:', person.name.FirstName) ; console.log('person.work.work:', person.work.work) ; console.log('person.work.workDescript:', person.work.workDescript) ; console.log('更改职位描述后的person.work.workDescript') ; person.work.changeDescripte('我在修改bug') ; console.log('person.work.workDescript:', person.work.workDescript) ; </script> </body>
相关文章推荐
- 设计模式知识连载(43)---参与者模式:
- 设计模式知识连载(7)---继承_3:优点结合-组合继承
- 设计模式知识连载(14)---工厂方法模式:
- 设计模式知识连载(5)---继承_1:子类的原型对象-类式继承
- 设计模式知识连载(28)---状态模式:
- 设计模式知识连载(35)---迭代器模式:
- 设计模式知识连载(3)---封装_2:闭包
- 设计模式知识连载(1)---函数的书写方式
- 设计模式知识连载(47)---Widget模式:
- 设计模式知识连载(40)---节流模式:
- 设计模式知识连载(42)---惰性模式:
- 设计模式知识连载(2)---封装_1
- 设计模式知识连载(19)---外观模式:
- 设计模式知识连载(48)---MVC模式:
- 设计模式知识连载(4)---封装_3:创建对象的安全模式
- 设计模式知识连载(21)---代理模式:
- 设计模式知识连载(26)---模板方法模式:
- 设计模式知识连载(32)---访问者模式:
- 设计模式知识连载(13)---简单工厂模式:
- 设计模式知识连载(20)---适配器模式: