享元模式
作者:互联网
#include <iostream> #include <memory> #include <unordered_map> class Flyweight { public: Flyweight(int data) : data_(data) {} void show() { std::cout << "In Flyweight show(). data_ is " << data_ << std::endl; } private: int data_ = 0; }; class FlyweightFactory { public: std::shared_ptr<Flyweight> getFlyweight(int data) { if (umf.find(data) != umf.end()) { std::cout << "In FlayweightFactory getFlayweight(). We have " << data << std::endl; } else { std::cout << "In FlayweightFactory getFlayweight(). We create " << data << std::endl; std::shared_ptr<Flyweight> f = std::make_shared<Flyweight>(data); umf.insert(std::make_pair(data, f)); } return umf.at(data); } private: std::unordered_map<int, std::shared_ptr<Flyweight>> umf; }; int main(int argc, char *argv[]) { FlyweightFactory ff; ff.getFlyweight(1); ff.getFlyweight(2); ff.getFlyweight(1);
return 1; }
标签:享元,std,getFlyweight,int,模式,umf,ff,data 来源: https://www.cnblogs.com/qiandeheng/p/15937185.html