-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFactoryDesignPattern.cpp
More file actions
86 lines (69 loc) · 1.44 KB
/
FactoryDesignPattern.cpp
File metadata and controls
86 lines (69 loc) · 1.44 KB
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
// Topic: Factory Pattern
// Standard: C++20
// Build: g++ -std=c++20 -o factory FactoryDesignPattern.cpp
#include <algorithm>
#include <cctype>
#include <iostream>
#include <memory>
#include <string>
class Shape
{
public:
virtual ~Shape() = default;
virtual void draw() const = 0;
};
class Circle : public Shape
{
public:
void draw() const override
{
std::cout << "Drawing Circle\n";
}
};
class Rectangle : public Shape
{
public:
void draw() const override
{
std::cout << "Drawing Rectangle\n";
}
};
class Triangle : public Shape
{
public:
void draw() const override
{
std::cout << "Drawing Triangle\n";
}
};
class ShapeFactory
{
public:
static std::unique_ptr<Shape> createShape(std::string type)
{
if (type == "circle")
return std::make_unique<Circle>();
if (type == "rectangle")
return std::make_unique<Rectangle>();
if (type == "triangle")
return std::make_unique<Triangle>();
return nullptr;
}
};
int main()
{
std::cout << "=== Factory Pattern ===\n\n";
auto circle = ShapeFactory::createShape("circle");
auto rectangle = ShapeFactory::createShape("rectangle");
auto triangle = ShapeFactory::createShape("triangle");
auto invalid = ShapeFactory::createShape("hexagon");
if (circle)
circle->draw();
if (rectangle)
rectangle->draw();
if (triangle)
triangle->draw();
if (!invalid)
std::cout << "Unknown shape type requested\n";
return 0;
}