Repository navigation
Expand file tree
/
Copy pathComposite.cpp
More file actions
94 lines (72 loc) · 2.31 KB
/
Copy pathComposite.cpp
File metadata and controls
94 lines (72 loc) · 2.31 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
87
88
89
90
91
92
93
94
#include <iostream>
#include <vector>
#include <string>
#include <memory>
#include <algorithm>
// Component Interface
class FileSystemItem {
public:
virtual ~FileSystemItem() = default;
virtual void print(int indent = 0) const = 0;
virtual size_t getSize() const = 0;
virtual void add(std::shared_ptr<FileSystemItem> item) {
throw std::runtime_error("Operation not supported on Leaf nodes.");
}
};
// Leaf Node (File)
class File : public FileSystemItem {
private:
std::string name;
size_t size;
public:
File(std::string name, size_t size)
: name(std::move(name)), size(size) {}
void print(int indent = 0) const override {
std::string padding(indent, ' ');
std::cout << padding << "- File: " << name << " (" << size << " KB)\n";
}
size_t getSize() const override {
return size;
}
};
// Composite Node (Directory)
class Directory : public FileSystemItem {
private:
std::string name;
std::vector<std::shared_ptr<FileSystemItem>> children;
public:
explicit Directory(std::string name) : name(std::move(name)) {}
void add(std::shared_ptr<FileSystemItem> item) override {
children.push_back(std::move(item));
}
void print(int indent = 0) const override {
std::string padding(indent, ' ');
std::cout << padding << "+ Directory: " << name << "/\n";
for (const auto& child : children) {
child->print(indent + 4);
}
}
size_t getSize() const override {
size_t total = 0;
for (const auto& child : children) {
total += child->getSize();
}
return total;
}
};
int main() {
auto root = std::make_shared<Directory>("Root");
auto file1 = std::make_shared<File>("config.json", 12);
auto file2 = std::make_shared<File>("index.html", 45);
root->add(file1);
root->add(file2);
auto subDir = std::make_shared<Directory>("images");
auto img1 = std::make_shared<File>("logo.png", 250);
auto img2 = std::make_shared<File>("banner.jpg", 1024);
subDir->add(img1);
subDir->add(img2);
root->add(subDir);
root->print();
std::cout << "\nTotal Root Directory Size: " << root->getSize() << " KB\n";
return 0;
}