享元模式(Flyweight):
运用共享技术有效地支持大量细粒度的对象。
2.享元模式可以避免大量非常相似类的开销。在程序设计中,有时就能够受到大幅度地减少需要实例化的类的数量。如果能把那些参数转移到类实例的外面,在方法调用时将他们传递进来,就可以通过共享大幅度地减少单个实例的数目。
享元模式实现代码:
#pragma once
#include <map>
#include <string>
#include <iostream>
using namespace std;
//Flyweight类,它是所有具体享元的超类或接口,通过这个接口,Flyweight可以接受并作用于外部状态。
class CFlyweight
{
public:
virtual void Operation(int nExtrinsicstate) = 0;
};
//CConcreteFlyweight是继承Flyweight超类或实现Flyweight接口,并为内部状态增加存储空间。
class CConcreteFlyweight : public CFlyweight
{
public:
void Operation(int nExtrinsicstate)
{
cout<<"ju ti Flyweight:"<<nExtrinsicstate<<endl;
}
};
//UnsharedConcreteFlyweight是指那些不需要共享的Flyweight子类。因为Flyweight接口共享称为可能,
//但它并不强制共享。
class CUnsharedConcreteFlyweight:public CFlyweight
{
public:
void Operation(int nExtrinsicstate)
{
cout<<"bu gong xiang de ju ti Flyweight:"<<nExtrinsicstate<<endl;
}
};
//FlyweightFactiry,是一个享元工厂,用来创建并管理Flyweight对象。它主要是用来确保合理地共享
//Flyweight,当用户请求一个Flyweigth时,FlyweightFactory对象提供一个已经创建的实例或者创建一个。
class CFlyweightFactory
{
private:
map<string ,CFlyweight *>m_mpFlyweight;
public:
CFlyweightFactory()
{
m_mpFlyweight.clear();
m_mpFlyweight["X"] = new CConcreteFlyweight();
m_mpFlyweight["Y"] = new CConcreteFlyweight();
m_mpFlyweight["Z"] = new CConcreteFlyweight();
}
~CFlyweightFactory()
{
delete m_mpFlyweight["X"];
delete m_mpFlyweight["Y"];
delete m_mpFlyweight["Z"];
}
CFlyweight * GetFlyweight(string strKey)
{
return m_mpFlyweight[strKey];
}
};
客户端调用:#include "stdafx.h"
#include <iostream>
#include <windows.h>
#include "FlyweightMode.h"
using namespace std;
int main()
{
int nExtrinsicstate = 22;
CFlyweightFactory *pF = new CFlyweightFactory();
CFlyweight *pNowFlyweight = pF->GetFlyweight("X");
pNowFlyweight->Operation(--nExtrinsicstate);
pNowFlyweight = pF->GetFlyweight("Y");
pNowFlyweight->Operation(--nExtrinsicstate);
pNowFlyweight = pF->GetFlyweight("Z");
pNowFlyweight->Operation(--nExtrinsicstate);
CUnsharedConcreteFlyweight *pUF = new CUnsharedConcreteFlyweight();
pUF->Operation(--nExtrinsicstate);
delete pUF;
delete pF;
return 0;
}
执行结果: