Qt C++ flyweight模式

来源:互联网 发布:屏幕录像软件 知乎 编辑:程序博客网 时间:2024/06/05 00:54

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();
}

原创粉丝点击