Qt_IM_54 - 8BitsCoding/RobotMentor GitHub Wiki
object를 만드는 과정(new)를 생략하고
그 관리를 하나의 object에서 하게 된다.
#include <QtCore/QCoreApplication>
#include <qdebug.h>
#include <qmetaobject.h>
#include <qmetatype.h>
#include "person.h"
/*
Builder design pattern
Build things in a uniform way = milliions of ways to do this.
*/
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QObject classroom;
QMetaEnum metaEnum = QMetaEnum::fromType<person::persontype>();
for (int i = 0; i < 10; i++) {
person::persontype type = person::persontype::STUDENT;
if (i == 0) type = person::persontype::PRINCIPAL;
if(i == 1) type = person::persontype::TEACHER;
person* p = person::build(type);
p->setParent(&classroom);
}
foreach(QObject * child, classroom.children()) {
person* p = qobject_cast<person*>(child);
if (p) qInfo() << p << " is a " << metaEnum.valueToKey(p->role());
}
return a.exec();
}// person.h
#pragma once
#include <QObject>
class person : public QObject
{
Q_OBJECT
public:
enum persontype { PRINCIPAL, TEACHER, STUDENT };
Q_ENUM(persontype)
static person* build(persontype type);
persontype role();
explicit person(QObject *parent = nullptr);
~person();
private:
persontype m_type;
};// person.cpp
#include "person.h"
person::person(QObject *parent)
: QObject(parent)
{
}
person::~person()
{
}
person* person::build(persontype type)
{
person* p = new person(nullptr);
p->m_type = type;
return p;
}
person::persontype person::role()
{
return m_type;
};