zoukankan      html  css  js  c++  java
  • Singleton 单例模式

    意图

    保证一个类仅有一个实例,并提供一个访问它的全局访问点。

    动机

    让类自身负责保存它的唯一实例。这个类可以保证没有其他实例可以被创建(通过截取创建新对象的请求) ,并且它可以提供一个访问该实例的方法。这就是Singleton模式。

    适用性

    • 当类只能有一个实例而且客户可以从一个众所周知的访问点访问它时。
    • 当这个唯一实例应该是通过子类化可扩展的,并且客户应该无需更改代码就能使用一个扩展的实例时。

    结构

    参与者

    定义一个Instance操作,允许客户访问它的唯一实例。Instance是一个类操作(即Smalltalk中的一个类方法和C + +中的一个静态成员函数) 

    协作

    客户只能通过Singleton的Instance操作访问一个Singleton的实例

    实现

    #include <iostream> 
    using namespace std;
    
    class Singleton
    {
    public:
        static Singleton * Instance();
        static void Destroy();
        void sayHello(){ cout << "hello" << endl; }
    protected:
        Singleton();
    private:
        static Singleton *m_pInstance;
    };
    
    Singleton * Singleton::m_pInstance = NULL;
    
    Singleton * Singleton::Instance()
    {
        if (m_pInstance == NULL)
            m_pInstance = new Singleton;
        return m_pInstance;
    }
    
    void Singleton::Destroy()
    {
        delete m_pInstance;
        m_pInstance = NULL;
    }
    
    Singleton::Singleton(){}
    
    int main()
    {
        Singleton::Instance()->sayHello();        //直接调用静态函数
        Singleton *p_s1 = Singleton::Instance();
        Singleton *p_s2 = Singleton::Instance();
        if (p_s2 == p_s1)
            cout << "same" << endl;        //输出same验证确实是单例
        else
            cout << "diff" << endl;
        system("pause");
    }

    要点:注意构造函数是保护性,试图直接实例化Singleton的客户将得到一个编译时的错误信息,这样就保证了仅有一个实例可以被创建

    另外一篇关于Singleton的好文章:

    http://www.cnblogs.com/loveis715/archive/2012/07/18/2598409.html

    http://www.cnblogs.com/liyuan989/p/4264889.html

  • 相关阅读:
    web.xml配置文件详解
    spring MVC配置文件详解
    路由导航刷新后导致当前选中的导航样式不见的解决办法
    vue input 使用v-model想要改变父属性的写法
    JS 编写一个指定范围内的随机数返回方法
    vue-router 3.1.5报错:vue-router.esm.js?8c4f:2089 Uncaught (in promise)
    Failed to mount component: template or render function not defined. vue
    vscode 操作debugger for chrome的配置文件写法
    JS操作DOM方法总结
    npm 代理配置的方法
  • 原文地址:https://www.cnblogs.com/raichen/p/5617632.html
Copyright © 2011-2022 走看看