# 享元模式(flyweight)

flyweight是輕量級的意思，中文這邊翻譯成享元，更容易讓人理解一些。

# 常用場景

1.當系統中有大量的細粒度對象實例，而且這些對象實例中有一些屬性是重復的情況下，考慮使用。

# 優點

1.提高了系統的效率，減小了內存的消耗。

2.減少了重復代碼。

3.減少了系統的復雜度。

# 缺點

1.維護共享對象和查找所需的共享對象需要花費很多時間。

# C++實現

` 1 #ifndef _FLYWEIGHT_H_ 2 #define _FLYWEIGHT_H_ 3  4  5 class FlyWeight 6 { 7 public: 8     FlyWeight(){}; 9     virtual ~FlyWeight(){};10 11     virtual void operation() = 0;12 13 };14 15 16 class ConcreteFlyWeight: public FlyWeight17 {18 public:19     ConcreteFlyWeight(){};20     ~ConcreteFlyWeight(){};21     22     void operation();23     24 };25 26 27 28 #endif`
FlyWeight.h
`1 #include "FlyWeight.h"2 #include <stdio.h>3 4 5 void ConcreteFlyWeight::operation()6 {7     printf("I'm ConcreteFlyWeight!\n");8 }`
FlyWeight.cpp
` 1 #ifndef _FLYWEIGHT_FACTORY_H_ 2 #define _FLYWEIGHT_FACTORY_H_ 3  4 #include <vector> 5 #include "FlyWeight.h" 6  7 using namespace std; 8  9 class FlyWeightFactory10 {11   public:12     FlyWeightFactory();13     ~FlyWeightFactory();14 15     FlyWeight* GetFlyWeight(int key);16 17   private:18     vector<FlyWeight*> m_flyWeights;//很多時候為了增加效率，使用hash表之類的結構，這里簡單的使用vector19 };20 21 #endif`
FlyWeightFactory.h
` 1 #include "FlyWeightFactory.h" 2  3 FlyWeightFactory::FlyWeightFactory() 4 { 5     FlyWeight* tmp = new ConcreteFlyWeight(); 6     m_flyWeights.push_back(tmp); 7 } 8  9 10 11 12 FlyWeightFactory::~FlyWeightFactory()13 {14     FlyWeight* tmp = m_flyWeights.at(0);15     delete tmp;16     tmp = NULL;17 }18 19 20 21 22 FlyWeight* FlyWeightFactory::GetFlyWeight(int key)23 {24     //簡單點表示25     return m_flyWeights.at(key);26 }`
FlyWeightFactory.cpp
` 1 #include "FlyWeightFactory.h" 2  3  4  5 int main() 6 { 7     FlyWeightFactory* factory = new FlyWeightFactory(); 8  9     FlyWeight* flyWeight = factory->GetFlyWeight(0);10     flyWeight->operation();11     return 0;12 }`
client.cpp
`g++ -o client client.cpp FlyWeight.cpp FlyWeightFactory.cpp`