构造函数可能非常复杂,例如:一个蛋糕,可能有各种形状、口味、尺寸、奶油、水果……构造函数需要接收大量参数,执行复杂的初始化过程(例如,需要大量条件判断这些参数是否为空)。为了解决这个问题,引入建造者模式,简化构造函数。

建造者模式需要三个关键组件

  • 目标类:比如class Car
  • 建造者:比如class CarBuilder,包含了构造车的各种方法
  • 监督者

构造者模式用于建造非常复杂的对象,因此,这个目标对象可能不遵循相同的接口

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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
class Car {
public:
std::vector<std::string> parts_; // 下划线用于区分成员变量和参数/局部变量
// std::unordered_map<std::string, std::string> parts_;
void listParts() const {
std::cout << "Car parts: ";
for (size_t i = 0; i < parts_.size(); i++) {
if (i == parts_.size() - 1) {
std::cout << parts_[i];
} else {
std::cout << parts_[i] << ", ";
}
}
std::cout << "\n\n";
}
};

class Builder {
public:
virtual void reset() = 0;
virtual void setSeats(...) = 0;
virtual void setEngine(...) = 0;
virtual void setTripComputer(...) = 0;
virtual void setGPS(...) = 0;
};

class CarBuilder : public Builder {
private:
Car* car_;
public:
CarBuilder(): car_(nullptr) {
reset();
}
void reset() {
if (car_) delete car_;
car_ = new Car();
}
void setSeats(...) {
// set num of seats in the car
}
void setEngine(...) {
// set engine type
}
void setTripComputer(...) {
// set Trip computer type
}
void setGPS(...) {
// install GPS
}
Car* getProduct() {
Car* car = car_;
reset();
return car;
}
};

class Director {
public:
Car* constructSportsCar(Builder& builder) {
builder.reset();
builder.setSeats(2);
builder.setEngine("someEngine");
builder.setTripComputer(true);
builder.setGPS(true);
return builder.getProduct();
}
Car* constructSUV(Builder& builder) {
// steps to build an SUV
}
};

int main(int argc, char* argv[]) {
CarBuilder builder = CarBuilder();
Director director = Director();
Car* newCar = director.constructSportsCar(builder);
newCar->listParts();
delete newCar;
return 0;
}