设计模式-结构型-享元
原创
©著作权归作者所有:来自51CTO博客作者shixin_0125的原创作品,请联系作者获取转载授权,否则将追究法律责任
#pragma once
#ifndef FLYWEIGHT_H
#define FLYWEIGHT_H
#include <string>
#include <list>
typedef std::string STATE;
class Flyweight
{
public:
virtual ~Flyweight(){}
STATE GetIntrinsicState();
virtual void Operation(STATE& ExtrinsicState) = 0;
protected:
Flyweight(const STATE& state)
:m_State(state)
{
}
private:
STATE m_State;
};
class FlyweightFactory
{
public:
FlyweightFactory(){}
~FlyweightFactory();
Flyweight* GetFlyweight(const STATE& key);
private:
std::list<Flyweight*> m_listFlyweight;
};
class ConcreateFlyweight : public Flyweight
{
public:
ConcreateFlyweight(const STATE& state)
: Flyweight(state)
{
}
virtual ~ConcreateFlyweight(){}
virtual void Operation(STATE& ExtrinsicState);
};
#endif
#include "StdAfx.h"
#include "flyweight_impl.h"
#include <iostream>
inline STATE Flyweight::GetIntrinsicState()
{
return m_State;
}
FlyweightFactory::~FlyweightFactory()
{
for (std::list<Flyweight*>::iterator iter = m_listFlyweight.begin();
iter != m_listFlyweight.end(); ++iter)
{
delete (*iter);
}
m_listFlyweight.clear();
}
Flyweight* FlyweightFactory::GetFlyweight(const STATE& key)
{
for (std::list<Flyweight*>::iterator iter = m_listFlyweight.begin();
iter != m_listFlyweight.end(); ++iter)
{
if ((*iter)->GetIntrinsicState() == key)
{
std::cout << "The Flyweight:" << key << " already exits"<< std::endl;
return (*iter);
}
}
std::cout << "Creating a new Flyweight:" << key << std::endl;
Flyweight* flyweight = new ConcreateFlyweight(key);
m_listFlyweight.push_back(flyweight);
return flyweight;
}
void ConcreateFlyweight::Operation(STATE& ExtrinsicState)
{
std::cout<<ExtrinsicState<<std::endl;
}
#include "stdafx.h"
#include "flyweight_impl.h"
#include <stdlib.h>
int _tmain(int argc, _TCHAR* argv[])
{
FlyweightFactory flyweightfactory;
flyweightfactory.GetFlyweight("hello");
flyweightfactory.GetFlyweight("world");
flyweightfactory.GetFlyweight("hello");
system("pause");
return 0;
}