单例模式的几种写法

来源:互联网 发布:淘宝可以卖自制食品吗 编辑:程序博客网 时间:2024/05/16 13:40

最简单的单例模式

singleton* getinstance(){    singleton instance;    if(instance==null)       instance=new singleton();    else        return instance;}

这种单例模式虽然简单,但不适用于多线程,当两个线程同事满足if语句的判断条件,就会创建多个实例。所以就有了加锁的单例模式

singleton* getinstance(){    lock();    singleton instance;    if(instance==null)        instance=new singleton();    unlock();    return instance;}

加锁的单例模式虽然防止创建多个实例,但会造成现成的阻塞,所以,大神们又想出了双重加锁模式的单例模式

singleton* getinstance(){    singleton instance;    if(instance==null)    {        lock();        if(instance==null)        {            instance=new singleton();        }        unlock();    }    return instance;}

这样的话,通过有极少的线程能同时通过第一个if语句并且被锁定,但是为了防止不同线程创建多个实例,又加了一个if,这样既不会造成线程的阻塞,也不会创建多个实例。

0 0
原创粉丝点击