標題起的是有點大git
主要是工做和學習中,遇到些朋友,怎麼說呢,代碼不夠Qt化github
多是因爲他們一開始接觸的是 Java MFC 吧安全
接觸 Qt 7個年頭了學習
但願個人系列文章能拋磚引玉吧spa
不少人洋洋灑灑寫了一大堆.net
好比這裏 http://xtuer.github.io/qtbook-singleton/線程
好比這裏 http://m.blog.csdn.net/Fei_Liu/article/details/69218935code
可是Qt自己就提供了專門的宏 Q_GLOBAL_STATIC對象
經過這個宏不但定義簡單,還能夠得到線程安全性。blog
rule.h
#ifndef RULE_H #define RULE_H class Rule { public: static Rule* instance(); }; #endif // RULE_H
rule.cpp
#include "rule.h" Q_GLOBAL_STATIC(Rule, rule) Rule* Rule::instance() { return rule(); }
寫法很簡單,用法也很簡單
在任何地方,引用頭文件 include "rule.h"
就能夠 Rule::instance()->xxxxxx()
主要是利用 Q_INVOKABLE 和 QMetaObject::newInstance
好比說你有一個Card類 card.h 和 2個派生的類
class Card : public QObject
{
Q_OBJECT
public:
explicit Card();
};
class CentaurWarrunner : public Card
{
Q_OBJECT
public:
Q_INVOKABLE CentaurWarrunner();
};
class KeeperoftheLight : public Card
{
Q_OBJECT
public:
Q_INVOKABLE KeeperoftheLight();
};
而後你寫一個 engine.h 和 engine.cpp
#ifndef ENGINE_H #define ENGINE_H #include <QHash> #include <QList> #include <QMetaObject> class Card; class Engine { public: static Engine* instance(); void loadAllCards(); Card* cloneCard(int ISDN); private: QHash<int, const QMetaObject*> metaobjects; QList<Card*> allcards; }; #endif // ENGINE_H
#include "engine.h" #include "card.h" Q_GLOBAL_STATIC(Engine, engine) Engine* Engine::instance() { return engine(); } void Engine::loadAllCards() { allcards << new CentaurWarrunner() << new KeeperoftheLight(); for (Card* card : allcards) { metaobjects.insert(card->getISDN(), card->metaObject()); } } Card* Engine::cloneCard(int ISDN) { const QMetaObject* meta = metaobjects.value(ISDN); if(meta == nullptr) { return nullptr; } return qobject_cast<Card*>(meta->newInstance()); }
這時,你就能夠在其餘cpp裏經過 Card* card = Engine::instance()->cloneCard(ISDN);
從不一樣的int值獲得不一樣的Card類型的對象
https://zhuanlan.zhihu.com/p/32109735