设计模式 - 单例模式(Singleton) C++实现

创建型模式

单例模式(Singleton)

意图:保证一个类只有一个实例,并提供一个访问它的全局访问点。
比如任务管理器就只需要一个实例。
如何来实现呢?可以把类的构造方法隐藏起来,设为private,然后类自身提供一个静态方法去获取实例。


实现:
#include <iostream>

using namespace std;

class Singleton {
private :
    Singleton() {
        cout << "create a instance" << endl;
    }
    static Singleton * _instance;

public :
    static Singleton * getInstance();
};

Singleton * Singleton::_instance = NULL;

Singleton * Singleton::getInstance() {
    if(_instance == NULL) {
        _instance = new Singleton();
    }
    return _instance;
}

int main() {
    Singleton * t1 = Singleton::getInstance();
    Singleton * t2 = t1->getInstance();
    Singleton & ref = * Singleton::getInstance();

    delete t1;

    return 0;
}


这个代码存在三个问题:
1. 复制构造函数、等号运算没有隐藏起来,还是会创建对象。比如
    Singleton a;
    Singleton b(a), c = a; 这是可以的
2. 线程不安全
3. 删除实例的时候,需要自己手动删除,而且很容易出错,不容易管理。
解决办法:
用static变量的特点,只初始化一次。

"
在C++memory model中对static local variable,说道:The initialization of such a variable is defined to occur the first time control passes through its declaration; for multiple threads calling the function, this means there’s the potential for a race condition to define first.
"


#include <iostream>

using namespace std;

class Singleton {
private :
    Singleton() {
        cout << "create a instance" << endl;
    }
    Singleton & operator = (const Singleton &);
    Singleton(const Singleton &);

public :
    ~Singleton() {
        cout << "destory" << endl;
    }
    static Singleton * getInstance();
};

Singleton * Singleton::getInstance() {
    static Singleton instance;
    return &instance;
}

int main() {
    Singleton * t1 = Singleton::getInstance();
    Singleton * t2 = t1->getInstance();
    Singleton & ref = * Singleton::getInstance();

    return 0;
}






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值