概念
将一个复杂对象的构建层与其表示层分离,同样的构建过程可以采用不同的并表示
与工厂模式的区别
工厂模式主要是为了创建对象实例或者类簇(抽象工厂),关心的是最终产出(创建)的是什么,而不关心创建的过程。
而建造者模式关心的是创建这个对象的整个过程,甚至于创建对象的每一个细节。 以下以创建应聘者为例:应聘者有兴趣爱好,姓名和期望的职位等等
解决的问题
方便用户创建复杂的对象(不需要知道实现过程)
代码复用性 & 封装性(将对象构建过程和细节进行封装 & 复用)
例子:
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 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
| function PersonBuilder(params) { this.skill = (params && params.skill) || "保密"; this.hbody = (params && params.hbody) || "保密"; } PersonBuilder.prototype = { getSkill: function () { console.log(this.skill); }, getHbody: function () { console.log(this.hbody); }, }; function Named(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.changeDescript = function (sentence) { this.workDescript = sentence; };
function Person(name, work) { var _person = new PersonBuilder(); _person.name = new Named(name); _person.work = new Work(work); return _person; } var person = new Person("xiao ming", "code"); console.log(person); person.work.changeDescript("更改描述!"); console.log(person.work.workDescript);
|