设计模式--单例设计模式

转自:https://blog.csdn.net/zh13544539220/article/details/48467095

参考:https://www.cnblogs.com/gccbuaa/p/7268313.html

 

单例模式是应用最多的一种设计模式,它要求每个类有且只能有一个实例对象,所以用C++设计一个单例模式的方法如下:

        1 构造函数声明为私有;   这样就保证了不能随意构造一个对象

        2 将拷贝构造函数与等号运算符声明为私有,并不提供他们的实现; 即禁止对象被拷贝。

        3 在类中声明一个静态的全局访问接口;

        4 声明一个静态的私有实例化指针;

class Singleton  
{  
public:  
    //全局访问接口  
    static Singleton *GetInstance()  
    {  
        if( instance_ == NULL )  
        {  
            instance_ = new Singleton;  
        }  
        return instance_;  
    }  
  
    ~Singleton()  
    {  
        cout << "~Singleton"<< endl;  
    }  
  
private:  
    Singleton(const Singleton& other);  
    Singleton & operator=(const Singleton & other);  
    Singleton()  
    {  
          cout << "Singleton"<<endl;  
    }  
  
  
    static Singleton *instance_; //引用性声明  
};  
  
Singleton * Singleton::instance_; //定义性声明  
  
int main(void)  
{  
    Singleton *s1 = Singleton::GetInstance();  
    Singleton *s2 = Singleton::GetInstance();  //s2的地址等于s1,即指向同一对象  
  
    //Singleton s3(*s1); //既然是单例模式,是不允许被拷贝的。编译会出错  
  
    return 0;  
}  

  

  上面就是单例类模式的C++实现,但是上述代码还有一个缺陷:单例类中申请的一些资源没有被释放,如instance_指向的空间没有被回收。一共有两种解决方式:

 

        第一种解决方式:

posted @ 2019-02-22 16:36  张三编程分享  阅读(125)  评论(0编辑  收藏  举报