design_patterns/04_builder.cpp
Yuki 5f6a05c86a
feat: Builder
Implemented a demo for the Builder.
2025-04-05 18:49:39 +08:00

68 lines
1.1 KiB
C++

#include <iostream>
#include <memory>
using namespace std;
class CPU {
public:
string type;
CPU(string s) {
type = s;
}
};
class Memory {
public:
string type;
Memory(string s) {
type = s;
}
};
class Computer {
unique_ptr<CPU> cpu;
unique_ptr<Memory> mem;
friend class Builder;
public:
void show() {
cout << "CPU: " << cpu->type << endl
<< "Memory: " << mem->type << endl;
}
};
class Builder {
public:
unique_ptr<Computer> c;
Builder() {
c = make_unique<Computer>();
}
// Method chaining
Builder& set_cpu(string s) {
c->cpu = make_unique<CPU>(s);
return *this;
}
Builder& set_mem(string s) {
c->mem = make_unique<Memory>(s);
return *this;
}
unique_ptr<Computer> build() {
// You can check if the computer is valid here.
return move(c);
}
};
int main() {
Builder b;
// You can pack `b.set().set()...build()` into a Director.
auto c = b
.set_cpu("Intel")
.set_mem("Samsung")
.build();
c->show();
}