作用:运用共享技术有效地支持大量细粒度的对象
UML结构图:
解析:
Flyweight模式在大量使用一些可以被共享的对象的时候使用。比如,在QQ聊天时很多时候你懒得回复又不得不回复,一般会用一些客套的话语敷衍别人,如“呵呵”,“好的”等待之类的,这些简单的答复其实每个人都是提前定义好的,在使用的时候才调用起来。
Flyweight就是基于解决这种问题的思路而产生的,当需要一个可以在其他地方共享使用的对象的时候,先去查询是否已经存在了同样的对象,如果没有就生成之;有的话就直接使用。
因此,Flyweight模式和Factory模式也经常混用。
实现:
需要说明的是下面的实现仅仅实现了对可共享对象的使用,非可共享对象的使用没有列出,因为这个不是Flyweight模式的重点。
这里的实现要点就是采用一个list链表来保存这些可以被共享的对象,需要使用的时候就到链表中查询是不是已经存在了,如果不存在就初始化一个,然后返回这个对象的指针。
(1)Flywight.h
[cpp] view
plaincopy
plaincopy
- #include <string>
- #include <list>
- typdef std::string STATE;
- class Flyweight
- {
- public:
- virtual ~Flyweight(){}
- STATE GetInstrinsicState();
- virtual void Operation(STATE &ExtrinsicState) = 0;
- protected:
- Flyweight(const STATE& state):m_State(state)
- {
- }
- private:
- STATE m_State;
- };
- class FlyweightFactory
- {
- public:
- FlyweightFactory(){}
- ~FlyweightFactory();
- Flyweight* GetFlyweight(const STATE& key);
- private:
- std::list<Flyweight*> m_listFlyweight;
- };
- class ConcreateFlyweight : public Flyweight
- {
- public:
- ConcreateFlyweight(const STATE& state) : Flyweight(state)
- {
- }
- virtual ~ConcreateFlyweight(){}
- virtual void Operation(STATE &ExtrinsicState);
- };
(2)Flyweight.cpp
[cpp] view
plaincopy
plaincopy
- #include "Flyweight.h"
- #include <iostream>
- inline STATE Flyweight::GetInstrinsicState()
- {
- return m_State;
- }
- FlyweightFactory::~FlyweightFactory()
- {
- std::list<Flyweight*>::iterator iter1, iter2, temp;
- for (iter1 = m_listFlyweight.begin();
- iter2 = m_listFlyweight.end();
- iter1 != iter2; )
- {
- temp = iter1;
- ++iter1;
- delete (*temp);
- }
- m_listFlyweight.clear();
- }
- Flyweight* FlyweightFactory::GetFlyweight(const STATE &key)
- {
- std::list<Flyweight*>::iterator iter1, iter2;
- for (iter1 = m_listFlyweight.begin(), iter2 = m_listFlyweight.end();
- iter1 != iter2;
- ++iter1)
- {
- if ((*iter1)->GetInstrinsicState() == key)
- {
- std::cout << "The Flyweight:" << key << "already exists" << std::endl;
- return (*iter1);
- }
- }
- std::cout << "Creating a new Flyweight:" << key << std::endl;
- Flyweight* flyweight = new ConcreateFlyweight(key);
- m_listFlyweight.push_back(flyweight);
- }
- void ConcreateFlyweight::Operation(STATE & ExtrinsicState)
- {
- }
(3)main.cpp
[cpp] view
plaincopy
plaincopy
- #include "FlyWeight.h"
- int main()
- {
- FlyweightFactory flyweightfactory;
- flyweightfactory.GetFlyweight("Hell");
- flyweightfactory.GetFlyweight("world");
- flyweightfactory.GetFlyweight("Hell");
- return 0;
- }