我的单例模式(C++)
时间:2011-03-23 来源:sharpfeng
单例模式类文件 Single.h Single.cpp
//Single.h
#pragma once
#include <iostream>
using namespace std;
class SingleClass
{
private:
SingleClass();
public:
static SingleClass* GetInstance()
{
if (instance == NULL)
{
instance = new SingleClass();
}
return instance;
}
private:
static SingleClass *instance;
class GcWorker
{
~GcWorker();
};
static GcWorker worker;
//以上是单例模式,下面是方法和属性
public:
void PrintAdd(int a,int b);
void PrintSub(int a,int b);
};
//Single.cpp
#include "Single.h"
SingleClass* SingleClass::instance = NULL;
SingleClass::SingleClass()
{
//初始化及一些状态
}
void SingleClass::PrintAdd( int a,int b )
{
cout<<"a + b = "<<a+b<<endl;
}
void SingleClass::PrintSub( int a,int b )
{
cout<<"a - b = "<<a-b<<endl;
}
SingleClass::GcWorker::~GcWorker()
{
if (SingleClass::instance != NULL)
{
delete SingleClass::instance;
SingleClass::instance = NULL;
}
}
客户端调用测试:
相关阅读 更多 +