C++与Qt实现设计模式——单例化

单例化实现:
1、私有化构造函数;
2、静态化私有指针变量;
3、建立静态public指针函数;
4、静态变量初始化。

例如:xxx.h函数定义如下:

class myTest : public QObject
{
	Q_OBJECT

public:
	static myTest* getInstance()// 静态指针函数
	{
		static QMutex ss;
		static QMutexLocker lock(&ss);
		if (mTest == NULL)
		{
			mTest = new myTest();
		}
		return mTest;
	}

	void testOut();
	
private:
	myTest(QObject *parent=0);// 私有化
	~myTest();

	static myTest* mTest;
	QMutex mtex;

};

xxx.cpp中初始化:

#include "mytest.h"

myTest::myTest(QObject *parent)
	: QObject(parent=0)
{

}

myTest::~myTest()
{

}

myTest* myTest::mTest = 0;

void myTest::testOut()
{

}

发布了56 篇原创文章 · 获赞 10 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/birenxiaofeigg/article/details/102940153