Repository navigation
Expand file tree
/
Copy pathPrototype.cpp
More file actions
105 lines (80 loc) · 2.72 KB
/
Copy pathPrototype.cpp
File metadata and controls
105 lines (80 loc) · 2.72 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
95
96
97
98
99
100
101
102
103
104
105
#include <iostream>
#include <memory>
#include <string>
#include <unordered_map>
// Prototype Interface
class Monster {
public:
virtual ~Monster() = default;
virtual std::unique_ptr<Monster> clone() const = 0;
virtual void print() const = 0;
virtual void setHealth(int health) = 0;
};
// Concrete Prototype 1
class Goblin : public Monster {
private:
std::string name;
int health;
int agility;
public:
Goblin(std::string name, int health, int agility)
: name(std::move(name)), health(health), agility(agility) {}
Goblin(const Goblin& other) = default;
std::unique_ptr<Monster> clone() const override {
return std::make_unique<Goblin>(*this);
}
void print() const override {
std::cout << "[Goblin] " << name << " | HP: " << health << " | Agility: " << agility << "\n";
}
void setHealth(int h) override { health = h; }
};
// Concrete Prototype 2
class Dragon : public Monster {
private:
std::string name;
int health;
int firePower;
public:
Dragon(std::string name, int health, int firePower)
: name(std::move(name)), health(health), firePower(firePower) {}
Dragon(const Dragon& other) = default;
std::unique_ptr<Monster> clone() const override {
return std::make_unique<Dragon>(*this);
}
void print() const override {
std::cout << "[Dragon] " << name << " | HP: " << health << " | Fire Power: " << firePower << "\n";
}
void setHealth(int h) override { health = h; }
};
// Prototype Registry / Manager
class MonsterRegistry {
private:
std::unordered_map<std::string, std::unique_ptr<Monster>> prototypes;
public:
void registerPrototype(const std::string& key, std::unique_ptr<Monster> prototype) {
prototypes[key] = std::move(prototype);
}
std::unique_ptr<Monster> createMonster(const std::string& key) const {
auto it = prototypes.find(key);
if (it != prototypes.end()) {
return it->second->clone();
}
return nullptr;
}
};
int main() {
MonsterRegistry registry;
registry.registerPrototype("weak_goblin",
std::make_unique<Goblin>("Goblin Scout", 50, 15));
registry.registerPrototype("red_dragon",
std::make_unique<Dragon>("Flame Dragon", 500, 100));
std::unique_ptr<Monster> g1 = registry.createMonster("weak_goblin");
std::unique_ptr<Monster> g2 = registry.createMonster("weak_goblin");
g2->setHealth(20);
std::unique_ptr<Monster> d1 = registry.createMonster("red_dragon");
std::cout << "--- Spawned Monsters ---\n";
g1->print();
g2->print();
d1->print();
return 0;
}