zoukankan      html  css  js  c++  java
  • 设计模式之实现---单件模式

    /*************************************

    CSingleton.h

    **************************************/

    #pragma  once
    #include <iostream>
    #include <string>
    using namespace std;

    class CSingleton
    {
    private:
     CSingleton(){
      cout<<"new instance created!"<<endl;
     };
     CSingleton(const CSingleton& _copyInst);
    private:
     static CSingleton* g_singleton;

    public:
     //这里是单键模式类的关键
     //我在这里实现的是对象的单件,而不是类的单件。
     //要实现类的单件的话,就必须要把类的成员都变为static.
     static CSingleton* getSingleton(){
      if(!g_singleton)
       g_singleton = new CSingleton();
      return g_singleton;
     }
    };

    /******************************************

    testclass.h

    *******************************************/

    #include "CSingleton.h"
    #include <iostream>
    using namespace std;

    class testSingleton
    {
    public:
     testSingleton(){
      CSingleton::getSingleton();
      cout<<"ok, called!"<<endl;
     }
    };

    /*******************************************

    CSingleton.cpp

    ********************************************/

    #include "CSingleton.h"

    CSingleton* CSingleton::g_singleton = NULL;

    /*******************************************

    testSingleton.cpp

    ********************************************/

    /*
     设计模式: 单件模式
     by 何戬, hejian@cad.zju.edu.cn
    */

    #include <iostream>
    #include "CSingleton.h"
    #include "testclass.h"
    using namespace std;

    int main()
    {
     CSingleton::getSingleton();
     CSingleton::getSingleton();

     //testSingleton newtest;

     return 0;
    }

  • 相关阅读:
    微信聊天框测试思路
    巧用&&和|| 让逻辑代码更简洁,逼格看起来更高一点(玩笑脸)
    获取URL中的参数
    解决移动端点击闪烁问题
    npm安装依赖包 --save-dev 和 --save; package.json的devDependencies和dependencies 的区别!
    vue-cli 3配置接口代理
    js小方法积累,将一个数组按照n个一份,分成若干数组
    web前端识别文字转语音
    html 锚点
    ES6 必须要用的数组Filter() 方法,不要再自己循环遍历了!!!
  • 原文地址:https://www.cnblogs.com/skyofbitbit/p/2756576.html
Copyright © 2011-2022 走看看