flyweight
来源:互联网 发布:棋牌类游戏的算法代码 编辑:程序博客网 时间:2024/06/01 07:55
作用:
运用共享技术有效地支持大量细粒度的对象。
运用共享技术有效地支持大量细粒度的对象。
解析:
Flyweight模式在大量使用一些可以被共享的对象的时候经常使用.比如,在QQ
聊天的时候很多时候你懒得回复又不得不回复的时候,一般会用一些客套的话语
敷衍别人,如"呵呵","好的"等等之类的,这些简单的答复其实每个人都是提前定
义好的,在使用的时候才调用出来.Flyweight就是基于解决这种问题的思路而
产生的,当需要一个可以在其它地方共享使用的对象的时候,先去查询是否已经
存在了同样的对象,如果没有就生成之有的话就直接使用.因此,Flyweight模式
和Factory模式也经常混用.
实现:
需要说明的是下面的实现仅仅实现了对可共享对象的使用,非可共享对象的使用
没有列出,因为这个不是Flyweight模式的重点.这里的实现要点是采用一个list
链表来保存这些可以被共享的对象,需要使用的时候就到链表中查询是不是已经
存在了,如果不存在就初始化一个,然后返回这个对象的指针.
1)Flyweight.h
#ifndef FLYWEIGHT_H
#define FLYWEIGHT_H
#include <string>
#include <list>
typedef std::string STATE;
class Flyweight
{
public:
virtual ~Flyweight(){}
STATE GetIntrinsicState();
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;
};
classConcreateFlyweight
: public Flyweight
{
public:
ConcreateFlyweight(const STATE& state)
: Flyweight(state)
{
}
virtual ~ConcreateFlyweight(){}
virtual void Operation(STATE&ExtrinsicState);
};
#endif
2)Flyweight.cpp
#include"FlyWeight.h"
#include<iostream>
inline STATEFlyweight::GetIntrinsicState()
{
return m_State;
}
FlyweightFactory::~FlyweightFactory()
{
std::list<Flyweight*>::iteratoriter1, 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*>::iteratoriter1, iter2;
for (iter1 = m_listFlyweight.begin(), iter2= m_listFlyweight.end();
iter1 != iter2;
++iter1)
{
if ((*iter1)->GetIntrinsicState() ==key)
{
std::cout << "TheFlyweight:" << key << " already exits"<<std::endl;
return (*iter1);
}
}
std::cout << "Creating a new Flyweight:"<< key << std::endl;
Flyweight* flyweight = newConcreateFlyweight(key);
m_listFlyweight.push_back(flyweight);
}
voidConcreateFlyweight::Operation(STATE& ExtrinsicState)
{
}
3)Main.cpp
#include"FlyWeight.h"
int main()
{
FlyweightFactory flyweightfactory;
flyweightfactory.GetFlyweight("hello");
flyweightfactory.GetFlyweight("world");
flyweightfactory.GetFlyweight("hello");
system("pause");
return 0;
}
- Flyweight
- Flyweight
- Flyweight
- flyweight
- flyweight
- flyweight
- Flyweight
- Flyweight
- Flyweight Pattern
- flyweight模式
- FlyWeight Pattern
- Flyweight模式
- FlyWeight模式
- Flyweight模式
- Flyweight模式
- Flyweight Design
- Flyweight 模式
- Flyweight模式
- hibernate中文查询 结果为空
- 什么是recovery?什么是fastboot?
- powershell List Folder and File hierarchy
- Oracle中的AS和IS的区别
- UBoot的POST(Power On Self Test)
- flyweight
- More Effective C++读书笔记7
- 10步让你成为更优秀的程序员
- Ubuntu编译内核
- Uboot中一些CONFIG_XXX定义说明
- @synthesize obj=_obj的理解
- ice介绍网上搜集整理
- 求三角形垂心重心
- ubuntu 自定义分辨率