-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbuilder_pattern.cpp
99 lines (81 loc) · 1.9 KB
/
builder_pattern.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
#include <memory>
#include <string>
class Engine
{
public:
explicit Engine(int power)
: mPower{power}
{
}
private:
int mPower = 0;
};
class Car
{
public:
enum class Type
{
Family,
Sport
};
using EnginePtr = std::unique_ptr<Engine>;
class Builder final
{
public:
using CarPtr = std::unique_ptr<Car>;
CarPtr create() const
{
return std::make_unique<Car>(mWeight, mWidth, mDoorCount, mColor);
}
Builder& setWeight(float value) noexcept
{
mWeight = value;
return *this;
}
Builder& setWidth(float value) noexcept
{
mWidth = value;
return *this;
}
Builder& setDoorCount(int value) noexcept
{
mDoorCount = value;
return *this;
}
Builder& setColor(std::string value) noexcept
{
mColor = std::move(value);
return *this;
}
private:
float mWeight = 2;
float mWidth = 4;
int mDoorCount = 4;
std::string mColor = "black";
};
Car(float weight, float width, int doorCount, std::string color, Type type, EnginePtr engine)
: mWeight{weight}
, mWidth{width}
, mDoorCount{doorCount}
, mColor{std::move(color)}
, mType{type}
, mEngine{std::move(engine)}
{
}
private:
float mWeight = 0;
float mWidth = 0;
int mDoorCount = 0;
std::string mColor;
Type mType = Type::Family;
EnginePtr mEngine;
};
int main()
{
auto car = Car::Builder{}
.setColor("blue")
.setDoorCount(2)
.setWidth(3.5f)
.create();
return 0;
}