本文主要是介绍Qt C++ composite模式,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
组合模式简单来说就是为了处理类似树型结构的方案设计,充分展示父子关系,精确查找各个item。
composite.h
#pragma once
#include <QDebug>
class CAbstractComposite
{
public:
virtual void operateName() = 0;
virtual void addItem(CAbstractComposite* item){Q_UNUSED(item)}
virtual void removeItem(CAbstractComposite* item){Q_UNUSED(item)}
virtual CAbstractComposite* findItem(const QString &name){Q_UNUSED(name) return 0;}
void setSex(const QString& sex){m_sex = sex;}
QString getSex() const{return m_sex;}
void setName(const QString& name){m_name = name;}
QString getName() const{return m_name;}
void setSalary(const QString& salary){m_salary = salary;}
QString getSalary() const{return m_salary;}
protected:
QString m_name;
QString m_sex;
QString m_salary;
};
class CItem : public CAbstractComposite
{
public:
CItem(QString name){m_name = name;}
void operateName();
};
class CSubComposite : public CAbstractComposite
{
public:
CSubComposite(QString name){m_name = name;}
void operateName();
void addItem(CAbstractComposite* item);
void removeItem(CAbstractComposite* item);
CAbstractComposite* findItem(const QString &name);
private:
QMap<QString,CAbstractComposite* > m_children;
};
composite.cpp
#include "composite.h"
void CItem::operateName()
{
qDebug() << m_name;
}
void CSubComposite::operateName()
{
qDebug() << m_name;
}
void CSubComposite::addItem(CAbstractComposite* item)
{
m_children.insert(item->getName(),item);
}
void CSubComposite::removeItem(CAbstractComposite* item)
{
m_children.remove(item->getName());
}
CAbstractComposite* CSubComposite::findItem(const QString &name)
{
return m_children.value(name);
}
main.cpp
#include <QApplication>
#include "composite.h"
int main(int argc,char **argv)
{
QApplication app(argc,argv);
CAbstractComposite* itemjj = new CItem("xiaojj");
itemjj->setSex("man");
itemjj->setSalary("1000");
CAbstractComposite* itemSky = new CSubComposite("sky");
itemSky->setSex("woman");
itemSky->setSalary("9000");
CAbstractComposite* itemBlue = new CItem("Blue");
itemBlue->setSex("man");
itemBlue->setSalary("3000");
CAbstractComposite* itemRed = new CItem("Red");
itemRed->setSex("man");
itemRed->setSalary("3000");
CAbstractComposite* itemYellow = new CItem("Yellow");
itemYellow->setSex("man");
itemYellow->setSalary("3000");
itemSky->addItem(itemRed);
itemSky->addItem(itemBlue);
itemSky->addItem(itemYellow);
CAbstractComposite* itemNew = itemSky->findItem("Yellow");
if (itemNew)
{
itemNew->operateName();
qDebug() << itemNew->getSalary();
}
return app.exec();
}
这篇关于Qt C++ composite模式的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!