首页 > 其他 > 详细

单例模式

时间:2016-09-09 16:32:46      阅读:137      评论:0      收藏:0      [点我收藏+]

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

示例一:该实现需要手动去销毁实例(实际使用中,常常忘记调用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:
    static Singleton* m_instance;
};

Singleton* Singleton::m_instance = nullptr;

 

示例二:

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

 

单例模式

原文:http://www.cnblogs.com/laogaoyang/p/5853285.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!