design_patterns/12_flyweight.cpp
Yuki 11df3146d7
feat: Flyweight
Implemented a demo for the Flyweight.
2025-04-13 03:27:24 +08:00

53 lines
998 B
C++

#include <iostream>
#include <memory>
#include <map>
using namespace std;
class Model {
string s;
public:
static int cnt;
Model(const string& s) : s(s) {
// Load model from file.
cout << "Loading model: " << s << endl;
cnt += 1;
}
};
int Model::cnt = 0;
class ModelFactory {
map<string, shared_ptr<Model>> cache;
public:
shared_ptr<Model> get_model(const string& s) {
auto it = cache.find(s);
if (it == cache.end()) {
auto ret = make_shared<Model>(s);
cache[s] = ret;
return ret;
}
return it->second;
}
};
struct Monster {
public:
int x;
int y;
shared_ptr<Model> t;
};
int main() {
ModelFactory f;
Monster m1{1, 1, f.get_model("pikachu")};
Monster m2{2, 1, f.get_model("pikachu")};
Monster m3{1, 2, f.get_model("snorlax")};
Monster m4{2, 2, f.get_model("pikachu")};
cout << "Create " << Model::cnt << " models in memory" << endl;
}