JavaScript 步进式建造者模式可以把复杂的对象创建过程变灵活, 不同的创建步骤像瀑布一下顺流而下,过程简介,清晰. 关键的一步 return this
let Person = function(name, surName, age, sex) {
this.name = name;
this.surName = surName;
this.age = age;
this.sex = sex;
}
let PersonBuilder = function () {
let name;
let surName;
let age;
let sex;
return {
setName: function (name) {
this.name = name;
return this;
},
setSurName: function (surName) {
this.surName = surName;
return this;
},
setAge: function (age) {
this.age = age;
return this;
},
setSex: function (sex) {
this.sex = sex;
return this;
},
build: function () {
return new Person(this.name, this.surName, this.age, this.sex);
}
};
};
let person = new PersonBuilder().setName('Tom').setSurName('Sawyer').setAge(12)
.setSex('male').build();
console.log(person);