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

    #include<iostream>
    #include <pthread.h>
    using namespace std;
    
    //该实例一直存在
    class Singleton
    {
    private:
        Singleton(){}
        Singleton(const Singleton&){}
        Singleton& operator=(const Singleton&){}
    public:
        static Singleton& GetInstance()
        {
            static Singleton s_instance;
            return s_instance;
        }
    };
    //用时创建,不用时销毁
    class Singleton2
    {
    private:
        Singleton2(){}
        Singleton2(const Singleton2&){}
        Singleton2& operator=(const Singleton2&){}
        static Singleton2* s_instance;
        static int s_counter;
        static pthread_mutex_t s_mutex;
    public:
        static Singleton2& GetInstance()
        {
            pthread_mutex_lock(&s_mutex);
            if(!s_instance) s_instance = new Singleton2();
            ++s_counter;
            pthread_mutex_unlock(&s_mutex);
            return *s_instance;
        }
        void ReleaseInstance(void)
        {
            pthread_mutex_lock(&s_mutex);
            if(s_counter&&--s_counter==0)
                delete this;
            pthread_mutex_unlock(&s_mutex);
        }
    };
    Singleton2 Singleton2::*s_instance = NULL;
    int Singleton2::s_counter = 0;
    pthread_mutex_t Singleton2::s_mutex = PTHREAD_MUTEX_INITIALIZER;
    
    int main()
    {
        Singleton2& s1 = Singleton2::GetInstance();
        Singleton2& s2 = Singleton2::GetInstance();
        s1.ReleaseInstance();
        s2.ReleaseInstance();
    
        return 0;
    }

    注:主要看思想,windows下好像不能编译。

  • 相关阅读:
    用算法合并数组
    Redis各个数据类型的使用场景
    seesion工作原理
    自删除道指令程序
    uva 1335
    《生活在Linux中》之:使用Bash就是使用Emacs
    手动配置S2SH三大框架报错(三)
    数据和C
    IOS之【地图MapKit】
    我工作这几年(五)-- Android学习4.5月总结(一)
  • 原文地址:https://www.cnblogs.com/jlyg/p/10399483.html
Copyright © 2011-2022 走看看