二十二、享元模式

享元模式(Flyweight)运用共享技术有效地支持大量细粒度的对象。

//Flyweight.h
#ifndef _FLYWEIGHT_H_
#define _FLYWEIGHT_H_
#include <iostream>
#include <string>
using namespace std;
class FlyWeight
{
public:
	virtual void Operation(const string& extrinsicState){}
	string GetIntrinsicState()
	{
		return _inSt;
	}
protected:
	FlyWeight(string insrinsicState)
	{
		_inSt = insrinsicState;
	}
private:
	string _inSt;
};
class ConcreteFlyweight:public FlyWeight
{
public:
	ConcreteFlyweight(string insrinsicState):FlyWeight(insrinsicState)
	{
		cout<<"ConcreteFlyweight Build..."<<insrinsicState<<endl;
	}
	void Operation(const string& extrinsicState)
	{
		cout<<"ConcreteFlyweight insrinsicState ["<<GetIntrinsicState()<<"] extrinsicState ["
			<<extrinsicState<<"]"<<endl;
	}
};
#endif

/*
	Flyweight.h
	一个享元工厂,用来创建并管理Flyweight对象。它主要是用来确保合理的共享
	Flyweight,当用户请求一个Flyweight时,Flyweight对象提供一个已创建的
	实例或者创建一个。
*/
#ifndef _FLYWEIGHTFACTORY_H_
#define _FLYWEIGHTFACTORY_H_
#include "Flyweight.h"
#include <vector>
#include <string>
using namespace std;
class FlyWeightFactory
{
public:
	FlyWeight* GetFlyweight(const string& key)
	{
		vector<FlyWeight*>::iterator it = _fly.begin();
		for (;it!=_fly.end();it++)
		{
			if ((*it)->GetIntrinsicState()==key)
			{
				cout<<"already created by users..."<<endl;
				return *it;
			}
		}
		FlyWeight* fn = new ConcreteFlyweight(key);
		_fly.push_back(fn);
		return fn;
	}
private:
	vector<FlyWeight*> _fly;
};
#endif

//main.cpp
#include "Flyweight.h"
#include "FlyweightFactory.h"

int main()
{
	FlyWeightFactory* fc = new FlyWeightFactory();
	FlyWeight* fw1 = fc->GetFlyweight("hello");
	FlyWeight* fw2 = fc->GetFlyweight("world!");
	FlyWeight* fw3 = fc->GetFlyweight("hello");

	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值