標題起的是有點大
主要是工作和學習中,遇到些朋友,怎么說呢,代碼不夠Qt化
可能是由於他們一開始接觸的是 Java MFC 吧
接觸 Qt 7個年頭了
希望我的系列文章能拋磚引玉吧
單例模式
很多人洋洋灑灑寫了一大堆
比如這里 http://xtuer.github.io/qtbook-singleton/
比如這里 http://m.blog.csdn.net/Fei_Liu/article/details/69218935
但是Qt本身就提供了專門的宏 Q_GLOBAL_STATIC
通過這個宏不但定義簡單,還可以獲得線程安全性。
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