feat: Simple Factory
Implement demo for simple factory.
This commit is contained in:
parent
fa1594968f
commit
91a99e3e25
3
.gitignore
vendored
Normal file
3
.gitignore
vendored
Normal file
@ -0,0 +1,3 @@
|
||||
bin
|
||||
.vscode
|
||||
a.out
|
||||
44
01_simple_factory.cpp
Normal file
44
01_simple_factory.cpp
Normal file
@ -0,0 +1,44 @@
|
||||
#include <iostream>
|
||||
#include <memory>
|
||||
|
||||
using namespace std;
|
||||
|
||||
class Shape {
|
||||
public:
|
||||
virtual void draw() = 0;
|
||||
};
|
||||
|
||||
class Circle : public Shape {
|
||||
public:
|
||||
virtual void draw() override {
|
||||
cout << "Circle draw" << endl;
|
||||
}
|
||||
};
|
||||
|
||||
class Square : public Shape {
|
||||
public:
|
||||
virtual void draw() override {
|
||||
cout << "Square draw" << endl;
|
||||
}
|
||||
};
|
||||
|
||||
class Factory {
|
||||
public:
|
||||
unique_ptr<Shape> generate(const string& s) {
|
||||
if (s == "circle") {
|
||||
return make_unique<Circle>();
|
||||
} else if (s == "square") {
|
||||
return make_unique<Square>();
|
||||
}
|
||||
|
||||
return nullptr;
|
||||
}
|
||||
};
|
||||
|
||||
int main() {
|
||||
Factory f;
|
||||
unique_ptr<Shape> s = f.generate("circle");
|
||||
s->draw();
|
||||
s = f.generate("square");
|
||||
s->draw();
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user