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