设计模式-FlyWeight
来源:互联网 发布:电子屏图文信息软件 编辑:程序博客网 时间:2024/06/07 18:42
FlyWeight模式在实现过程中主要是要为共享对象提供一个对象池,其中有一个类似Factory模式的对象构造工厂,当用户需要一个对象的时候,会象工厂发出一个请求对象的消息,工厂会通过对象池遍历池中的对象,如果有直接返回,没有于是创建。
1、抽象享元(Flyweight)角色:此角色是所有的具体享元类的基类,为这些类规定出需要实现的公共接口,通过这个接口Flyweight可以接受并作用于外部状态。2、具体享元(ConcreteFlyweight)角色:实现抽象享元角色所规定的接口。如果有内蕴状态(Intrinsic State)的话,必须负责为内蕴状态提供存储空间。享元对象的内蕴状态必须与对象所处的周围环境无关,从而使得享元对象可以在系统内共享的。
3、享元工厂(FlyweightFactory)角色:本角色负责创建和管理享元角色。本角色必须保证享元对象可以被系统适当地共享。当一个客户端对象调用一个享元对象的时候,享元工厂角色会检查系统中是否已经有一个复合要求的享元对象。如果已经有了,享元工厂角色就应当提供这个已有的享元对象;如果系统中没有一个适当的享元对象的话,享元工厂角色就应当创建一个合适的享元对象。
4、客户端(Client)角色:本角色需要维护一个对所有享元对象的引用。本角色需要自行存储所有享元对象的外蕴状态。
#include <iostream>
#include <string>
#include <vector>
#include <cassert>
using namespace std; class FlyWeight
{
public:
virtual ~FlyWeight(){}
virtual void Operation(const string& exState){}
string GetInsState(){return this->_insState;}
protected:
FlyWeight(string insState)
{this->_insState=insState;}
private:
string _insState;
}; class ConFlyweight:public FlyWeight
{
public:
ConFlyweight(string insState):FlyWeight(insState)
{cout<<"ConFlyweight Build "<< insState<<endl;}
~ConFlyweight(){};
void Operation(const string& exState)
{
cout<<this->GetInsState()<<endl;
cout<<exState<<endl;
}
}; class FlyWeightFactory
{
public:
FlyWeightFactory(){}
~FlyWeightFactory(){}
FlyWeight* GetFlyweight(const string& key)
{
vector<FlyWeight*>::iterator it=_fly.begin();
for(;it!=_fly.end();it++)
{
if((*it)->GetInsState()==key)
{
cout<<"Have Created"<<endl;
return *it;
}
}
FlyWeight* fn=new ConFlyweight(key);
_fly.push_back(fn);
return fn;
}
private:
vector<FlyWeight*> _fly;
}; void main()
{
FlyWeightFactory *fw=new FlyWeightFactory();
FlyWeight* fw1=fw->GetFlyweight("Jackill");
FlyWeight* fw2=fw->GetFlyweight("Rukawa");
FlyWeight* fw3=fw->GetFlyweight("Jackill");
}
- 设计模式 - Flyweight模式
- 设计模式--FlyWeight 模式
- 设计模式-- Flyweight
- Flyweight设计模式
- 设计模式之 flyweight
- Flyweight设计模式
- 设计模式-FlyWeight
- 设计模式11 - Flyweight
- JAVA设计模式-FlyWeight
- 设计模式之FlyWeight
- Flyweight 设计模式
- Structual设计--Flyweight模式
- 设计模式之FlyWeight
- 设计模式之Flyweight
- c++ FlyWeight 设计模式
- 设计模式之FlyWeight模式
- 设计模式学习11 Flyweight
- java设计模式10:Flyweight
- 编译器错误消息: CS0201: 只有 assignment、call、increment、decrement 和 new 对象表达式可用作语句
- 【转】PrintStream 和 PrintWriter的区别
- Anroid 界面边框圆角的实现方式
- 字符,字节,和编码
- page cache ,buffer cache,swap space
- 设计模式-FlyWeight
- SetROP2函数 ——设置前景色与背景色
- linux中Oops信息的调试及栈回溯—Linux人都知道,这是好东西!
- WEB原型设计工具Mockup
- 多玩YY靠屌丝用户突出腾讯重围成功上市
- poj 2029
- 真正优秀的程序员有哪些与众不同之处?
- 使用 windbg 分析 minidump
- jquery始终显示DIV中央