Qt 单例模式:本身就提供了专门的宏 Q_GLOBAL_STATIC 通过这个宏不但定义简单,还可以获得线程安全性


单例模式

很多人洋洋洒洒写了一大堆

但是Qt本身就提供了专门的宏Q_GLOBAL_STATIC

通过这个宏不但定义简单,还可以获得线程安全性。

rule.h

1 #ifndef RULE_H 2 #define RULE_H 3 4 class Rule 5 ; 9 10 #endif // RULE_H

rulepp

1 #include "rule.h" 2 3 Q_GLOBAL_STATIC(Rule, rule) 4 5 Rule* Rule::instance() 6

写法很简单,用法也很简单

在任何地方,引用头文件 include "rule.h"

就可以 Rule::instance()>xxxxxx()


抽象工厂模式

主要是利用Q_INVOKABLE和QMetaObject::newInstance

比如说你有一个Card类card.h和 2个派生的类

1 class Card : public QObject 2 ; 7 class CentaurWarrunner : public Card 8 ; 13 class KeeperoftheLight : public Card 14 ;

然后你写一个engine.henginepp

1 #ifndef ENGINE_H 2 #define ENGINE_H 3 4 #include <QHash> 5 #include <QList> 6 #include <QMetaObject> 7 8 class Card; 9 10 class Engine 11 ; 21 22 #endif // ENGINE_H
1 #include "engine.h" 2 #include "card.h" 3 4 Q_GLOBAL_STATIC(Engine, engine) 5 6 Engine* Engine::instance() 7 10 11 void Engine::loadAllCards() 12 19 } 20 21 Card* Engine::cloneCard(int ISDN) 22 28 return qobject_cast<Card*>(meta>newInstance()); 29 }

这时,你就可以在其他cpp里通过 Card* card = Engine::instance()>cloneCard(ISDN);

从不同的int值得到不同的Card类型的对象



上一篇:Qt 解析命令行(QCommandLineOption和QCommandLineParser类)

下一篇:ITK 计算质心


Qt
Copyright © 2002-2019 k262电脑网 www.k262.cn 皖ICP备2020016292号
温馨提示:部分文章图片数据来源与网络,仅供参考!版权归原作者所有,如有侵权请联系删除!QQ:251442993 热门搜索 网站地图