#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;
}