zoukankan      html  css  js  c++  java
  • 剑指offer-2.单例模式

    0 问题

    实现一个单例模式

    1 分析

    实现单例模式的关键在于:

    1. 将构造函数设置为private,或是protected
    2. 创建一个静态函数,调用构造函数。
    3. 使用一个静态成员变量保存单例对象
    4. 因为只能在堆上分配内存,因此需要一个函数显式的调用析构函数

    2 实现

    class Singleton 
    {
    public:
        static Singleton* get()
        {
            if(obj==nullptr)
            {
                MuteLock lock(mutex);
                if(obj==nullptr)
                {
                    obj=new Singleton;
                }
            }
            return obj
        }
        
        ~Singleton();
        static void free()
        {
            delete obj;
        }
    
    private:
        Singleton();
    
        static Singleton* obj;
        Mutex mutex;
    };
    
    static Singleton* Singleton::obj=nullptr;

    3 拓展

    模板单例模式。派生自本模板的子类都是单例模式。

    template <typename T>
    class Singleton
    {
    public:
        static Singleton* get()
        {
            if(obj==nullptr)
            {
                MuteLock lock(mutex);
                if(obj==nullptr)
                {
                    // 注意这里是new 的 T
                    obj=new T;
                }
            }
            return obj
        }
        
        ~Singleton();
        static void free()
        {
            delete obj;
        }
    
    // 构造函数变为 protected , 因为子类构造函数要调用基类的构造函数。
    protected:
        Singleton();
    private:
        static Singleton* obj;
        Mutex mutex;
    };
    
    static Singleton* Singleton::obj=nullptr;
    
    class Derive : public Singleton<Derive>
    {
        // 声明为 友元,因为基类的 get() ,要new 自己,因此基类需要能够访问到自己的构造函数
        friend Singleton<Derive>;
    private:
        Derive();
    public:
    };
  • 相关阅读:
    在CentOS 6上安装Apache和PHP
    花10分钟看一看,少走30年的弯路
    IOS开发之UITabBarController与UINavigationController混合使用
    重构tableview!
    初学IOS之TableView
    关于mac下配置mysql心得
    类,对象,方法的
    shell脚本
    关于我
    机器学习&深度学习视频资料汇总
  • 原文地址:https://www.cnblogs.com/perfy576/p/8555075.html
Copyright © 2011-2022 走看看