iT邦幫忙

2023 iThome 鐵人賽

DAY 13
0
自我挑戰組

設計模式系列 第 13

Day13 - 享元模式(Flyweight pattern)

  • 分享至 

  • xImage
  •  

介紹
享元模式透過共享物件來減少資源使用。此模式將物件分為內部及外部狀態。內部狀態是固定的,可分享給大家使用,外部狀態則隨外在環境改變,並由外在環境維護。

C++範例

#include <iostream>
#include <unordered_map>

class Flyweight
{
public:
    virtual void Show(int ext) = 0;
};

class ConcreteFlyweight : public Flyweight
{
public:
    void Show(int ext) override
    {
        std::cout << "flyweight concret object, external state: " << ext << std::endl;
    }
};

class FlyweightFactory
{
public:
    Flyweight *GetFlyweight(int key)
    {
        if (m_flyweights.find(key) == m_flyweights.end())
        {
            m_flyweights[key] = new ConcreteFlyweight();
        }
        return m_flyweights[key];
    }

private:
    std::unordered_map<int, Flyweight *> m_flyweights;
};

int main()
{
    FlyweightFactory factory;
    Flyweight *fw1 = factory.GetFlyweight(1);
    fw1->Show(10);

    Flyweight *fw2 = factory.GetFlyweight(2);
    fw2->Show(20);

    Flyweight *fw3 = factory.GetFlyweight(1);
    fw3->Show(30);

    delete fw1;
    delete fw2;

    return 0;
}

Output:

flyweight concret object, external state: 10
flyweight concret object, external state: 20
flyweight concret object, external state: 30

Ref:
https://blog.csdn.net/bigger_belief/article/details/132302054


上一篇
Day12 - 裝飾者模式(Decorator pattern)
下一篇
Day14 - 代理模式(Proxy pattern)
系列文
設計模式30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言