标签:作用 back 结构 pause class return 创建 外部 ali
1) 意图:
运用共享技术有效的支持大量细粒度的对象。(理解享元模式,主要是对象被分解成intrinsic和extrinsic两部分,即内部的共享状态和外部状态)
2) 结构:
其中:
3) 适用性:
4) 举例:
1 #include <iostream> 2 #include <list> 3 class Flyweight 4 { 5 public: 6 Flyweight() {} 7 virtual ~Flyweight() {} 8 virtual std::string getKey() { return ""; } 9 virtual void Operation(std::string extrinsicStr) = 0; 10 }; 11 class ConcreteFlyweight : public Flyweight 12 { 13 public: 14 ConcreteFlyweight() {} 15 ConcreteFlyweight(std::string str):m_inState(str) {} 16 virtual ~ConcreteFlyweight() {} 17 virtual std::string getKey() 18 { 19 return m_inState; 20 } 21 virtual void Operation(std::string extrinsicStr) 22 { 23 std::cout << extrinsicStr.c_str() << std::endl; 24 std::cout << m_inState.c_str() << std::endl; 25 } 26 private: 27 std::string m_inState; 28 }; 29 class FlyweightFactory 30 { 31 public: 32 FlyweightFactory() {} 33 virtual ~FlyweightFactory() {} 34 Flyweight* GetFlyweight(std::string key) 35 { 36 std::list<Flyweight*>::iterator it = m_listFly.begin(); 37 for (; it != m_listFly.end(); ++it) 38 { 39 if ((*it)->getKey() == key) 40 { 41 return (*it); 42 } 43 } 44 Flyweight* ptr = new ConcreteFlyweight(key); 45 m_listFly.push_back(ptr); 46 return ptr; 47 } 48 private: 49 std::list<Flyweight*> m_listFly; 50 }; 51 52 int main() 53 { 54 FlyweightFactory* factory = new FlyweightFactory(); 55 Flyweight* fly = factory->GetFlyweight("hello"); 56 fly->Operation("World"); 57 system("pause"); 58 }
标签:作用 back 结构 pause class return 创建 外部 ali
原文地址:https://www.cnblogs.com/ho966/p/12231971.html