#pragma once
#include "stdafx.h"
#include<map>
#include<set>
#include<string>
#include<iostream>
using namespace std;
/*
设计模式-享元模式(Flyweight)
运用共享技术有效地支持大量细粒度的对象。
*/
class CFlyweight {//所有具体享元的超类或接口。通过这个接口,Flyweight可以接受并作用域外部状态。
public:
virtual void Operation(const int &nExtrinsicstat) = 0;
};
class CConcreteFlyweight :public CFlyweight {//为内部状态增加存储空间。
public:
void Operation(const int &nExtrinsicstate) {
cout << "ju ti Flyweight:" << nExtrinsicstate << endl;
}
};
class CUnsharedconcreteFlyweight :public CFlyweight {
public:
void Operation(const int &nExtrinsicstate) {
cout << "bu gong xiang de ju ti Flyweight:" << nExtrinsicstate << endl;
}
};
class CFlweightFactory {//享元工厂,用来创建并管理Flyweight对象。
private:
map<string, CFlyweight*>mmpFlyweight;
public:
CFlweightFactory() {
mmpFlyweight.clear();
mmpFlyweight["X"] = new CConcreteFlyweight();
mmpFlyweight["Y"] = new CConcreteFlyweight();
mmpFlyweight["Z"] = new CConcreteFlyweight();
}
~CFlweightFactory() {
delete mmpFlyweight["X"];
delete mmpFlyweight["Y"];
delete mmpFlyweight["Z"];
}
CFlyweight * GetFlyweight(string strKey) {
return mmpFlyweight[strKey];
}
};
int main() {
int nExtrinsicstate = 10;
CFlweightFactory *pFac = new CFlweightFactory();
CFlyweight *pNowFlyweight = pFac->GetFlyweight("X");
pNowFlyweight->Operation(--nExtrinsicstate);
pNowFlyweight = pFac->GetFlyweight("Y");
pNowFlyweight->Operation(--nExtrinsicstate);
pNowFlyweight = pFac->GetFlyweight("Z");
pNowFlyweight->Operation(--nExtrinsicstate);
pNowFlyweight = new CUnsharedconcreteFlyweight();
pNowFlyweight->Operation(--nExtrinsicstate);
delete pFac, delete pNowFlyweight;
getchar();
return 0;
}