享元模式

#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; }

 

上一篇:ssh连接远程服务器


下一篇:C项目---图书管理系统