flyweight.h
#pragma once
#include <QDebug>
class CFlyweightBase
{
public:
virtual void operate() = 0;
virtual QString getText() const{return m_text;}
protected:
CFlyweightBase(QString text){m_text = text;}
QString m_text;
};
class CConcreateFly : public CFlyweightBase
{
public:
CConcreateFly(QString text):CFlyweightBase(text){}
void operate()
{
qDebug() << m_text;
}
};
class CFlyWeightFactory
{
public:
CFlyWeightFactory(){}
~CFlyWeightFactory()
{
qDeleteAll(m_lst.begin(),m_lst.end());
}
CFlyweightBase* getFlyweight(const QString& text);
private:
QList<CFlyweightBase*> m_lst;
};
flyweight.cpp
#include "flyweight.h"
CFlyweightBase* CFlyWeightFactory::getFlyweight(const QString& text)
{
QListIterator<CFlyweightBase*> iter(m_lst);
while(iter.hasNext())
{
CFlyweightBase* ptr = iter.next();
if (ptr->getText() == text)
{
qDebug() << text << " already exits";
return ptr;
}
}
CFlyweightBase* new_ptr = new CConcreateFly(text);
m_lst.append(new_ptr);
return new_ptr;
}
main.cpp
#include <QApplication>
#include "flyweight.h"
int main(int argc,char **argv)
{
QApplication app(argc,argv);
CFlyWeightFactory *fac = new CFlyWeightFactory;
fac->getFlyweight("hello");
fac->getFlyweight("data");
fac->getFlyweight("hello");
delete fac;
return app.exec();
}