设计模式之单件模式 singleton

来源:互联网 发布:java课程多少钱 编辑:程序博客网 时间:2024/06/07 21:20
Singleton(单件)模式是一种很常用的设计模式。单件类在整个应用程序的生命周期中只能有一个实例存在,使用者通过一个全局的访问点来访问该实例。这是Singleton的两个最基本的特征。

单件模式 singleton C++ 实现:

Singleton.h
#ifndef SINAGLETON_H#define SINAGLETON_H//单件模式关class SingletonClass{protected://constructSingletonClass();//destruct~SingletonClass();public://get instancestatic SingletonClass *Instance();    //destroy instancestatic void Destory(void);//test functionvoid 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;//constructSingletonClass::SingletonClass(){//}//destructSingletonClass::~SingletonClass(){Destory();}//get instanceSingletonClass *SingletonClass::Instance(){if (NULL == m_pcInstance){m_pcInstance = new SingletonClass();}return m_pcInstance;}//destroy instancevoid 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;}

上面的代码是没有采取互斥处理的,可以把采用临界区的方法实现,比较简单在此不详述。