Builder 模式

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
let Human = function (param) {
this.skill = (param && param.skill) || "null"
this.hobby = (param && param.skill) || "null"
}
Human.prototype = {
getSkill: function () {
return this.skill
},
getHobby: function () {
return this.hobby
},
}

let Named = function (name) {
let _this = this
;((name, _this) => {
this.wholeName = name
if (name.indexOf(" ") > -1) {
_this.FirstName = name.slice(0, name.indexOf(" "))
_this.LastName = name.slice(name.indexOf(" "))
}
})(name, _this)
}

let Work = function (work) {
let _this = this
;((work, _this) => {
switch (work) {
case "code":
this.work = "developer"
break
case "design":
this.work = "designer"
break
default:
this.work = work
}
})(work, _this)
}

Work.prototype.changeWork = function (work) {
this.work = work
}

/**
* to create a Person
* @param {*} name
* @param {*} work
*/
let Person = function (name, work) {
let _person = new Human()
_person.name = new Named(name)
_person.work = new Work(work)
return _person
}

// for test
let person = new Person("Jack Edward", "design")
console.log(person.work)
console.log(person.name)
person.work.changeWork("code")
console.log(person.work)