Flyweight

来源:互联网 发布:cocos2d js引擎 编辑:程序博客网 时间:2024/06/05 23:59

          


 原链接:http://www.cppblog.com/converse/
#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

实现文件

inline STATE Flyweight::GetIntrinsicState()
{
return m_State;
}

FlyweightFactory::~FlyweightFactory()
{
std::list<Flyweight*>::iterator iter1, iter2, temp;


for (iter1 = m_listFlyweight.begin(), iter2 = m_listFlyweight.end();
iter1 != iter2;
)
{
temp = iter1;
++iter1;
delete (*temp);
}


m_listFlyweight.clear();
}

Flyweight* FlyweightFactory::GetFlyweight(const STATE& key)
{
std::list<Flyweight*>::iterator iter1, iter2;


for (iter1 = m_listFlyweight.begin(), iter2 = m_listFlyweight.end();
iter1 != iter2;
++iter1)
{
if ((*iter1)->GetIntrinsicState() == key)
{
std::cout << "The Flyweight:" << key << " already exits"<< std::endl;
return (*iter1);
}
}


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)
{


}

main函数的调用:

int main()
{
FlyweightFactory flyweightfactory;
flyweightfactory.GetFlyweight("hello");
flyweightfactory.GetFlyweight("world");
flyweightfactory.GetFlyweight("hello");
system("pause");
return 0;
}

输出结果:

   

个人的建议:采用智能指针改进,即链表list存放智能指针:

注:以下粉红色部分未更改部分,其余不变。

class FlyweightFactory
{
...

private:
std::list<shared_ptr<Flyweight>>m_listFlyweight;
};

FlyweightFactory::~FlyweightFactory()
{


m_listFlyweight.clear();
}

Flyweight* FlyweightFactory::GetFlyweight(const STATE& key)
{
std::list<shared_ptr<Flyweight>>::iterator iter1, iter2;


for (iter1 = m_listFlyweight.begin(), iter2 = m_listFlyweight.end();
iter1 != iter2;
++iter1)
{
if (*(*iter1)->GetIntrinsicState() == key)
{
std::cout << "The Flyweight:" << key << " already exits"<< std::endl;
return *(*iter1);
}
}


std::cout << "Creating a new Flyweight:" << key << std::endl;
shared_ptr<Flyweight>flyweight= new ConcreateFlyweight(key);
m_listFlyweight.push_back(flyweight);
return  *flyweight;
}






0 0
原创粉丝点击