文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>我的单例模式(C++)

我的单例模式(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;
    }
}

客户端调用测试:

#include "Single.h"
 
int main()
{
    SingleClass::GetInstance()->PrintAdd(2,5);
    SingleClass::GetInstance()->PrintSub(5,2);
    cout<<endl<<"Over!"<<endl;
}

结果:

排行榜 更多 +
辰域智控app

辰域智控app

系统工具 下载
网医联盟app

网医联盟app

运动健身 下载
汇丰汇选App

汇丰汇选App

金融理财 下载