-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathmain.cpp
111 lines (84 loc) · 2.07 KB
/
main.cpp
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
/*
* @FileName : main.cpp
* @CreateAt : 2022/4/5
* @Author : Inno Fang
* @Email : innofang@yeah.net
* @Description:
*/
#include <iostream>
#include <string>
class Product {
public:
size_t getId() const {
return _id;
}
void setId(size_t id) {
_id = id;
}
double getWeight() const {
return _weight;
}
void setWeight(double weight) {
_weight = weight;
}
const std::string &getType() const {
return _type;
}
void setType(const std::string &type) {
_type = type;
}
friend std::ostream &operator<<(std::ostream &os, const Product &product) {
os << "id: " << product._id << " weight: " << product._weight << " type: " << product._type;
return os;
}
private:
size_t _id;
double _weight;
std::string _type;
};
class Builder {
public:
virtual void buildId(size_t id) = 0;
virtual void buildWeight(double weight) = 0;
virtual void buildType(const std::string &type) = 0;
virtual Product *create() = 0;
};
class ConcreteBuilder : public Builder {
public:
ConcreteBuilder()
: _product(new Product()) {}
void buildId(size_t id) override {
_product->setId(id);
}
void buildWeight(double weight) override {
_product->setWeight(weight);
}
void buildType(const std::string &type) override {
_product->setType(type);
}
Product *create() override {
return _product;
}
private:
Product *_product;
};
class Director {
public:
explicit Director(Builder *builder)
: _builder(builder) {}
void construct(size_t id, double weight, const std::string &type) {
_builder->buildId(id);
_builder->buildWeight(weight);
_builder->buildType(type);
}
private:
Builder *_builder;
};
int main() {
Builder *builder = new ConcreteBuilder();
auto *director = new Director(builder);
director->construct(1, 12.3, "typeA");
Product *product = builder->create();
std::cout << *product << std::endl;
return 0;
}