-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOpenClosedPrinciple.cpp
More file actions
82 lines (69 loc) · 1.74 KB
/
OpenClosedPrinciple.cpp
File metadata and controls
82 lines (69 loc) · 1.74 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
// Open Closed Principle
// Software entities should be open for extension but closed for modification.
// In other words, the behavior of a module can be extended without modifying its source code.
// This principle is achieved by using interfaces and abstract classes.
#include <iostream>
#include <string>
#include <vector>
#include <typeinfo>
// Without OCP
class Rectangle
{
public:
double width, height;
Rectangle(double w, double h) : width(w), height(h) {}
};
class Circle
{
public:
double radius;
Circle(double r) : radius(r) {}
};
class AreaCalculator
{
public:
void calculate_area(const std::vector<void *> &shapes)
{
for (const auto &shape : shapes)
{
if (typeid(*shape) == typeid(Rectangle))
{
Rectangle *rect = static_cast<Rectangle *>(shape);
std::cout << "Rectangle area: " << rect->width * rect->height << std::endl;
}
else if (typeid(*shape) == typeid(Circle))
{
Circle *circle = static_cast<Circle *>(shape);
std::cout << "Circle area: " << 3.14 * circle->radius * circle->radius << std::endl;
}
}
}
};
// With OCP
class Shape
{
public:
virtual float calculate_area() = 0;
};
class Rectangle : public Shape
{
private:
float width, height;
public:
Rectangle(float w, float h) : width(w), height(h) {}
float calculate_area() override
{
return width * height;
}
};
class Circle : public Shape
{
private:
float radius;
public:
Circle(float r) : radius(r) {}
float calculate_area() override
{
return radius * radius * 3.14;
}
};