个人理解的应用场景
举个例子,比如想要创建各种类型的车的实例,车的类型有很多种,但创建每种类型车的接口定义可能是一样的,就用到了此模式
相关概念的通俗解释
- 上述例子中接口的定义叫builder
- 接口到每种类型的车的具体实现叫concrete builder
- 真正用于创建车的类叫director
实现模式的思路
1.首先要定义builder的接口
2.然后各个concretebuilder类去实现这个接口
3.director中接收一个builder实例作为参数,最后返回一个一类车的实例
示例代码
function Director() {
this.construct = function (builder) {
builder.step1();
builder.step2();
return builder.get();
}
}
//由于js不支持接口,我个人认为其实应当typescript定义一个接口,然后下面两个类去实现这个接口
function CarBuilder() {
this.car = null;
this.step1 = function () {
this.car = new Car();
};
this.step2 = function () {
this.car.addParts();
};
this.get = function () {
return this.car;
};
}
function TruckBuilder() {
this.truck = null;
this.step1 = function () {
this.truck = new Truck();
};
this.step2 = function () {
this.truck.addParts();
};
this.get = function () {
return this.truck;
};
}
function Car() {
this.doors = 0;
this.addParts = function () {
this.doors = 4;
};
this.say = function () {
log.add("I am a " + this.doors + "-door car");
};
}
function Truck() {
this.doors = 0;
this.addParts = function () {
this.doors = 2;
};
this.say = function () {
log.add("I am a " + this.doors + "-door truck");
};
}
//其他开发者使用代码段
new Director().construct(new CarBuilder());
原文地址:https://www.cnblogs.com/zhangrenjian/p/8552288.html
时间: 2024-10-15 05:33:00