天天看點

設計模式學習筆記-結構型模式-Flyweight 模式

設計模式學習筆記-結構型模式-Flyweight 模式

Flyweight.h

#pragma once

#include <string>
using namespace std;

class Flyweight
{
public:
	~Flyweight();

	virtual void Operation(const string& extrinsicState);

	string GetIntrinsicState();

protected:
	Flyweight(string intrinsicState);

private:
	string _intrinsicState;//内在的
};

class ConcreteFlyWeight:public Flyweight
{
public:
	ConcreteFlyWeight(string intrinsicState);

	~ConcreteFlyWeight();

	void Operation(const string& extrinsicState);

protected:
private:
};
           

Flyweight.cpp

#include "Flyweight.h"
#include <iostream> 
using namespace std;

Flyweight::~Flyweight()
{
}

void Flyweight::Operation(const string & extrinsicState)
{
}

string Flyweight::GetIntrinsicState()
{
	return _intrinsicState;
}

Flyweight::Flyweight(string intrinsicState)
{
	_intrinsicState = intrinsicState;
}

ConcreteFlyWeight::ConcreteFlyWeight(string intrinsicState):Flyweight(intrinsicState)
{
	cout << "ConcreteFlyweight Build....."<<intrinsicState<<endl;
}

ConcreteFlyWeight::~ConcreteFlyWeight()
{
}

void ConcreteFlyWeight::Operation(const string & extrinsicState)
{
	cout << "ConcreteFlyweight: 内 蘊["<<this->GetIntrinsicState()<<"] 外 蘊["<<extrinsicState<<"]"<<endl;
}
           

FlyWeightFactory.h

#pragma once

#include "Flyweight.h"
#include <string>
#include <vector>
using namespace std;

class FlyWeightFactory
{
public:
	FlyWeightFactory();
	~FlyWeightFactory();

	Flyweight* GetFlyweight(const string& key);

private:
	vector<Flyweight*> _fly;
};
           

FlyWeightFactory.cpp

#include "FlyWeightFactory.h"
#include <iostream> 
using namespace std;


FlyWeightFactory::FlyWeightFactory()
{
}


FlyWeightFactory::~FlyWeightFactory()
{
}

Flyweight * FlyWeightFactory::GetFlyweight(const string & key)
{
	auto iter = _fly.begin();
	for (; iter != _fly.end(); iter++)
	{
		if ((*iter)->GetIntrinsicState() == key)
		{
			cout << "already created by users...."<<endl;
			return *iter;
		}
	}
	Flyweight* fn = new ConcreteFlyWeight(key);
	_fly.push_back(fn);
	return fn;
}
           

main.cpp

#include <iostream>
#include "FlyWeightFactory.h"
using namespace std;

int main(int argc, char* argv[])
{
	/*Flyweight 模式
	在實作過程中主要是要為共享對象提供一個存放的“倉庫”(對象池),
	這裡是通過 C++ STL 中 Vector 容器*/
	FlyWeightFactory* fc = new FlyWeightFactory();

	Flyweight* fw1 = fc->GetFlyweight("hhhhh");
	Flyweight* fw2 = fc->GetFlyweight("lllll");
	Flyweight* fw3 = fc->GetFlyweight("hhhhh");

	ConcreteFlyWeight* fw4 = new ConcreteFlyWeight("2");
	fw4->Operation("1");

	system("pause");
	return 0;
}
           
ConcreteFlyweight Build.....hhhhh
ConcreteFlyweight Build.....lllll
already created by users....
ConcreteFlyweight Build.....2
ConcreteFlyweight: 内 蘊[2] 外 蘊[1]
請按任意鍵繼續. . .
           

Flyweight 模式主要是要為共享對象提供一個存放的“倉庫”(對象池),可以避免建立大量重複的對象,減少造成的存儲開銷

繼續閱讀