DesignPatterns(01)Singleton

来源:互联网 发布:飘零网络验证系统 编辑:程序博客网 时间:2024/06/15 23:05

这里展示的是最简单的Singleton(单例模式),不考虑多线程,因此也就没有考虑线程安全和加锁的话题了。

Singleton类的定义

//Singleton Definitionclass Singleton{public:    static Singleton* getInstance();private:    Singleton(){        std::cout<<"the first time constructor is shown"<<std::endl;    };    static Singleton* instance;};//Xcode中要加上这句话才能编译通过,要给全局变量和类的静态变量初始化为0才能在Xcode中编译通过。Singleton* Singleton::instance=NULL;Singleton * Singleton::getInstance() {if (!instance) {instance = new Singleton();};return instance;};


main函数中对Singleton类的使用

int main(int argc, const char * argv[]){    Singleton* p1=Singleton::getInstance();    Singleton* p2=Singleton::getInstance();    if(p1==p2)        std::cout << "Hello, World!\n";    return 0;}


输出如下:

the first time constructor is shownHello, World!Program ended with exit code: 0




0 0
原创粉丝点击