意图:
运用共享技术有效的支持大量细粒度对象
适用性:
1一个应用程序使用了大量的对象
2由于使用大量的对象造成很大的开销
3对象的大多数状态都可变为外部状态
4如果删除对象的外部状态,可以用相对较少的共享对象,取代很多组对象
5应用程序不依赖于对象标识
效果:
使用FLYWEIGHT模式后,传输查找和计算外部状态都会产生开销,然而空间上的节省抵消了这些开销。
1因为共享,实例总数减少的数目
2对象内部状态的平均数目
3外部状态存储
实现:
1删除外部状态 外部状态有一个单独的对象结构计算得到,且该结构的存储要求非常小
2管理共享对象 对象共享,用户不能直接实例化。FlyWeight可以帮助用户查找某个特定的FlyWeight对象,若不存在,则创建一个FlyWeight。还包括引用计数和垃圾回收
Flyweight.h
- #include <string>
- #include <iostream>
- using namespace std;
- const int MAX_GLYPH_NUM = 128;
- class GlyphContext
- {
- public:
- GlyphContext(){size=1;font=1;}
- virtual ~GlyphContext(){size=0;font=0;};
- int size;
- int font;
- };
- class Glyph
- {
- public:
- Glyph()
- {cout<<"Glyph is created"<<endl;
- m_content="0";
- }
- virtual ~Glyph(){cout<<"Glyph is destoryed"<<endl;}
- virtual void Draw(GlyphContext& ct)
- {cout<<"Draw "<<m_content<<" with size="<<ct.size<<",font="<<ct.font<<endl;}
- virtual string GetContent(){return m_content;}
- virtual void SetContent(string s){m_content=s;}
- private:
- string m_content;
- };
- class GlyphFactory
- {
- public:
- GlyphFactory();
- virtual ~GlyphFactory();
- virtual Glyph* CreateString(string s);
- private:
- Glyph* m_listGlyph[MAX_GLYPH_NUM];
- };
Flyweight.cpp
- #include "FlyWeight.h"
- Glyph* GlyphFactory::CreateString(string s)
- {
- bool all_null = true;
- int i;
- for (i=0;(i<MAX_GLYPH_NUM)&&(m_listGlyph[i]!= 0);i++)
- {
- if ( m_listGlyph[i]->GetContent() == s)
- {
- cout<<s<<" has already exists"<<endl;
- return m_listGlyph[i];
- }
- }
- if (i < MAX_GLYPH_NUM)
- {
- m_listGlyph[i] = new Glyph;
- m_listGlyph[i]->SetContent(s);
- cout<<s<<" is new added"<<endl;
- return m_listGlyph[i];
- }
- }
- GlyphFactory::GlyphFactory()
- {
- for (int i=0;i<MAX_GLYPH_NUM;i++)
- {
- m_listGlyph[i]=0;
- }
- }
- GlyphFactory::~GlyphFactory()
- {
- for (int i=0;(i<MAX_GLYPH_NUM)&&(m_listGlyph[i]!= 0);i++)
- {
- delete m_listGlyph[i];
- m_listGlyph[i]=0;
- }
- }
main.cpp
- #include <string>
- #include <iostream>
- using namespace std;
- #include "FlyWeight.h"
- int main()
- {GlyphFactory a;
- Glyph* b;
- GlyphContext c;
- b =a.CreateString("Hello");
- b->Draw(c);
- b=a.CreateString("World");
- b->Draw(c);
- b = a.CreateString("Hello");
- b->Draw(c);
- return 0;
- }