c++ 结构型模式-享元(Flyweight)

1) 意图:

运用共享技术有效的支持大量细粒度的对象。(理解享元模式,主要是对象被分解成intrinsicextrinsic两部分,即内部的共享状态和外部状态)

2) 结构:

 

 

 其中:

  1. Flyweight描述一个接口,通过这个接口Flyweight可以接受并作用于外部状态
  2. ConcreteFlyweight实现Flyweight接口,并为内部状态增加存储空间
  3. UnsharedConcreteFlyweight不需要共享的外部状态
  4. FlyweightFactory创建并管理Flyweight对象

 3) 适用性:

  1. 一个应用程序使用大量的对象
  2. 完全由于使用大量的对象,造成很大的开销
  3. 对象的大多数状态可以变成外部状态
  4. 用相对较少的共享对象取代很多组对象
  5. 应用程序不依赖于对象表示

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  }

 

posted @ 2020-01-24 11:36  ho966  阅读(174)  评论(0编辑  收藏  举报