单例模式:Qt自己就提供了专门的宏 Q_GLOBAL_STATIC 经过这个宏不但定义简单,还能够得到线程安全性

标题起的是有点大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

相关文章
相关标签/搜索