不考虑该设计模式本身的概念,先感受以下两段代码带来的感受先。
class Frog {
constructor(name, weight, height, gender) {
this.name = name
this.weight = weight // in lbs
this.height = height // in inches
this.gender = gender
}
eat(target) {
console.log(`Eating target: ${target.name}`)
}
}
class FrogBuilder {
constructor(name, gender) {
this.name = name
this.gender = gender
}
setWeight(weight) {
this.weight = weight
return this
}
setHeight(height) {
this.height = height
return this
}
build() {
if (!('weight' in this)) {
throw new Error('Weight is missing')
}
if (!('height' in this)) {
throw new Error('Height is missing')
}
return new Frog(this.name, this.weight, this.height, this.gender)
}
}
const leon = new FrogBuilder('Leon', 'male')
.setWeight(14)
.setHeight(3.7)
.build()
由上面的两段代码可以看出,Builder Pattern 主要用来当构建函数传入的参数过于复杂的情况下,进行的代码优化的手段。抽离出不必要的东西,而后在相应的函数中赋予该实例其他的属性。
用 TS 来写
export interface User {
name: string;
age: number;
}
export class UserBuilder {
private readonly _user: User;
constructor() {
this._user = {
name: "",
age: 0
};
}
name(name: string): UserBuilder {
this._user.name = name;
return this;
}
age(age: number): UserBuilder {
this._user.age = age;
return this;
}
build(): User {
return this._user;
}
}
const userWithName: User = new UserBuilder()
.name("John")
.build();
const userWithGender: User = new UserBuilder()
.gender("Female")
.build();