存在大量细粒度对象的系统中,使用享元模式可以减少对相同对象的创建。

    image.png

    1. #include <iostream>
    2. #include <memory>
    3. #include <unordered_map>
    4. #include <utility>
    5. class Flyweight {
    6. public:
    7. virtual void Print() = 0;
    8. virtual ~Flyweight() = default;
    9. };
    10. class ConcreteFlyweight : public Flyweight {
    11. public:
    12. explicit ConcreteFlyweight(char key) : key_(key) {}
    13. void Print() override { std::cout << key_<<'\n'; }
    14. private:
    15. char key_;
    16. };
    17. class FlyweightFactory {
    18. public:
    19. std::unique_ptr<Flyweight>& FlyweightPtr(char c) {
    20. if (const auto it = m_.find(c); it != std::end(m_)) {
    21. std::cout << "existing key:";
    22. return it->second;
    23. }
    24. std::unique_ptr<Flyweight> p = std::make_unique<ConcreteFlyweight>(c);
    25. m_.emplace(c, std::move(p));
    26. return m_.at(c);
    27. }
    28. private:
    29. std::unordered_map<char, std::unique_ptr<Flyweight>> m_;
    30. };
    31. int main() {
    32. FlyweightFactory factory;
    33. factory.FlyweightPtr('a')->Print(); // a
    34. factory.FlyweightPtr('a')->Print(); // existing key: a
    35. factory.FlyweightPtr('b')->Print(); // b
    36. factory.FlyweightPtr('b')->Print(); // existing key: a
    37. }