单例模式

单例模式::  只实例化一次对象     分为饿汉式单例类和懒汉式单例类。
一般结合工厂模式使用
优点:
1.减少了时间和空间的开销(new)
2.提高了封装性,使得外部不易改动实例
 
单线程中:
 
Singleton* getinstance()
{
    if(instance == NULL)
{
instance = new Singleton();
}
 
return instance;
}
多线程加锁: 影响性能  容易造成大量线程的阻塞
 
Singleton* getinstance()
{
    lock();
    if(instance == NULL)
{
instance = new Singleton();
}
unlock();
 
return instance;
}
 
双重锁定::
 
Singleton* getinstance()
{
    if(instance == NULL)
{
lock();
    if(instance == NULL)
{
instance = new Singleton();
}
    unlock();
}
return instance;
}
 
 
posted @ 2021-07-16 01:08  Azuki_op  阅读(23)  评论(0)    收藏  举报