设计模式—享元模式(二十二)

        软件领域中的设计模式的重要性不言而喻。设计模式中运用了面向对象编程语言的重要特性:封装、继承、多态。虽然知道这些特性的定义但是并没有做到真正的理解,这样特性有什么作用?用于什么场合中等等问题,带着疑问开始学习设计模式,主要参考《大话设计模式》和《设计模式:可复用面向对象软件的基础》两本书。

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

设计模式—享元模式(二十二)_第1张图片

        FlyweightFactory:一个享元工厂,用来创建并管理Flyweight对象,它主要是用来确保合理地共享Flyweight,当用户请求一个Flyweight时,FlyweightFactory对象提供一个已创建的实例或者创建一个(如果不存在的话)

        Flyweight:所有具体享元类的超类或接口,通过这个接口,Flyweight可以接受并作用于外部状态。

        ConcreteFlyweight:继承Flyweight超类或者实现Flyweight接口,并为内部状态增加存储空间。

        UnshareConcreteFlyweight:指那些不需要共享的Flyweight子类,因为Flyweight接口共享成为可能,但它并不强制共享。

#include 
#include 
#include 
#include
using namespace std;
class Flyweight
{
public:
	virtual void Operation(int extrinsicState) = 0;
};
class ConcreteFlyweight :public Flyweight
{
public:
	virtual void Operation(int extrinsicState) override
	{
		cout << "具体共享的Flyweight:" << extrinsicState << endl;
	}
};
//不需共享的Flyweight子类
class UnshareConcreteFlyweight :public Flyweight
{
public:
	virtual void Operation(int extrinsicState) override
	{
		cout << "不共享的Flyweight:" << extrinsicState << endl;
	}
};

//享元工厂
class FlyweightFactory
{
private:
	map m_hash;
public:
	FlyweightFactory()
	{
		m_hash["X"] = new ConcreteFlyweight();
		m_hash["Y"] = new ConcreteFlyweight();
		m_hash["Z"] = new ConcreteFlyweight();
	}
	Flyweight* GetFlyweight(string key)
	{
		return m_hash[key];
	}
};

//客户端
int main()
{
	int extrsicstate = 22;

	FlyweightFactory* f = new FlyweightFactory();
	Flyweight* fx = f->GetFlyweight("X");
	fx->Operation(extrsicstate++);
	
	Flyweight* fy = f->GetFlyweight("X");
	fy->Operation(extrsicstate++);
	
	Flyweight* fz = f->GetFlyweight("X");
	fz->Operation(extrsicstate++);

	UnshareConcreteFlyweight* uf = new UnshareConcreteFlyweight();
	uf->Operation(extrsicstate++);

	return 0;
}

你可能感兴趣的:(设计模式)