Singleton(单件)模式是一种很常用的设计模式。单件类在整个应用程序的生命周期中只能有一个实例存在,使用者通过一个全局的访问点来访问该实例。这是Singleton的两个最基本的特征。
单件模式 singleton C++ 实现:
Singleton.h
#ifndef SINAGLETON_H #define SINAGLETON_H //单件模式关 class SingletonClass{ protected: //construct SingletonClass(); //destruct ~SingletonClass(); public: //get instance static SingletonClass *Instance(); //destroy instance static void Destory(void); //test function void DoSomething(void); private: static SingletonClass * m_pcInstance; }; #endif
Singleton.cpp
// Singleton.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include "Singleton.h" #include <iostream> #include <string> using namespace std; SingletonClass * SingletonClass::m_pcInstance = NULL; //construct SingletonClass::SingletonClass() { // } //destruct SingletonClass::~SingletonClass() { Destory(); } //get instance SingletonClass *SingletonClass::Instance() { if (NULL == m_pcInstance) { m_pcInstance = new SingletonClass(); } return m_pcInstance; } //destroy instance void SingletonClass::Destory() { if (NULL != m_pcInstance) { delete m_pcInstance; m_pcInstance = NULL; } } void SingletonClass::DoSomething(void) { // } int main(int argc, char* argv[]) { SingletonClass::Instance()->DoSomething(); SingletonClass::Instance()->Destory(); return 0; }
上面的代码是没有采取互斥处理的,可以把采用临界区的方法实现,比较简单在此不详述。