class Product{ // 具体产品
constructor(){
this.name = null;
this.type = null;
}
setName(name){
this.name = name;
}
setType(type){
this.type = type;
}
showProduct(){
console.log("name:", this.name);
console.log("type:", this.type);
}
}
class Builder{ // 抽象建造者
setPart(name, type){
throw new Error("Abstract method cannot be called");
}
getProduct(){
throw new Error("Abstract method cannot be called");
}
}
class ConcreteBuilder extends Builder{ // 实体建造者
constructor(){
super();
this.product = new Product();
}
build(name, type){
this.product.setName(name);
this.product.setType(type);
}
getProduct(){
return this.product;
}
}
class Director{ // 指挥者
constructor(){
this.builder = new ConcreteBuilder();
}
getProductA(){
this.builder.build("A", "TypeA");
return this.builder.getProduct();
}
getProductB(){
this.builder.build("B", "TypeB");
return this.builder.getProduct();
}
}
(function() {
var director = new Director();
var productA = director.getProductA();
productA.showProduct(); // name: A type: TypeA
var director = new Director();
var productB = director.getProductB();
productB.showProduct(); // name: B type: TypeB
})()