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

    单例模式就是该类只允许有一个类实例,如下示例一,是一个常见的实现方式。

    示例一:该实现需要手动去销毁实例(实际使用中,常常忘记调用DestroyInstance()销毁实例)

    class Singleton
    {
    public:
        static Singleton* GetInstance() 
        {
            if (nullptr == m_instance)
            {
                m_instance = new Singleton();
            }
            
            return m_instance;
        }
    
        static DestroyInstance()
        {
            if (nullptr != m_instance)
            {
                delete m_instance;
                m_instance = nullptr;
            }
        }
    private:
        Singleton(){}
        static Singleton* m_instance;
    };
    
    Singleton* Singleton::m_instance = nullptr;

    示例二:该实现程序结束时,系统会调用该类的析构函数,销毁实例

    class Singleton
    {
    public:
        static Singleton* GetInstance() 
        {
            static Singleton instance;       
            return &instance;
        }
    private:
       Singleton(){} 
    };

    备注:c++0x后不用考虑多线程的问题,由编译器保证静态变量的线程安全性。

    在孤独中思考,在思考中成熟,在成熟中升华
  • 相关阅读:
    三大范式
    html 横线的代码
    CSS下拉 菜单3.27第一次
    JS页面三种打开方式及对话框
    函数整理
    3.22整理作业
    for循环,if 练习
    php测试题
    设计模式
    面向对象的三大特性
  • 原文地址:https://www.cnblogs.com/laogaoyang/p/5853285.html
Copyright © 2011-2022 走看看