zoukankan      html  css  js  c++  java
  • C++之单例类模板

    单例类模板:一个类只能有一个对象,比如超市收银系统中清点物品的仪器只有一个

    设计思路:

      1.构造函数,拷贝构造函数必须设计为private,防止自己生成新的对象

      2.且类的指针要设计为static类型,并初始化为NULL

      3.当需要使用对象时(即访问类指针)

        空值:则重新分配对象

        非空值:返回当前所指向的对象

    代码如下

     1 #include<iostream>
     2 
     3 using namespace std;
     4 
     5 //扫描物品的工具类 
     6 class SObject
     7 {
     8 private:
     9     static SObject* c_instance;
    10     SObject(const SObject&);
    11     SObject& operator=(const SObject&);
    12     SObject()
    13     {
    14         
    15     }
    16 public:
    17     static SObject* GetInstance();
    18     void print()
    19     {
    20         cout << "this = " << this << endl;
    21     }
    22 };
    23 
    24 //初始化指针 
    25 SObject* SObject::c_instance=NULL;
    26 
    27 //类似于构造函数 
    28 SObject* SObject::GetInstance()
    29 {
    30     if(c_instance==NULL)
    31         c_instance=new SObject();
    32         
    33     return c_instance;
    34 }
    35 
    36 int main()
    37 {
    38     SObject *s1=SObject::GetInstance();
    39     SObject *s2=SObject::GetInstance();
    40     
    41     s1->print();
    42     s2->print();
    43     
    44     return 0;
    45 }

    锦上添花之笔:考虑到可扩展性,我们可以用模板来实现

    头文件内写上泛型类,利用友元类来实现

    头文件:

     1 #ifndef SINGLEEXAMPLE_H_
     2 #define SINGLEEXAMPLE_H_
     3 
     4 template<typename T>
     5 class Singleexample
     6 {
     7 private:
     8     static T* point;
     9 public:
    10     static T* Instance();
    11 };
    12 
    13 template<typename T>
    14 T* Singleexample<T>::point = NULL;
    15 
    16 template<typename T>
    17 T* Singleexample<T>::Instance()
    18 {
    19     if (point == NULL)
    20         point = new T();
    21 
    22     return point;
    23 }
    24 
    25 #endif

    主文件

     1 #include<iostream>
     2 #include"Singleexample.h"
     3 
     4 using namespace std;
     5 
     6 class Obeject
     7 {
     8     friend class Singleexample<Obeject>;
     9 private:
    10     Obeject(){}
    11     Obeject(const Obeject&){}
    12     Obeject& operator=(const Obeject&){}
    13 public:
    14     void print()
    15     {
    16         cout << "this = " << this << endl;
    17     }
    18 };
    19 
    20 int main()
    21 {
    22     Obeject* s1=Singleexample<Obeject>::Instance();
    23     Obeject* s2=Singleexample<Obeject>::Instance();
    24 
    25     s1->print();
    26     s2->print();
    27 
    28     return 0;
    29 }
  • 相关阅读:
    对于数据的测试
    绕过前端,直接调用后端接口的可能性
    API接口自动化之3 同一个war包中多个接口做自动化测试
    API接口自动化之2 处理http请求的返回体,对返回体做校验
    API接口自动化之1 常见的http请求
    DB中字段为null,为空,为空字符串,为空格要怎么过滤取出有效值
    Linux 常用的压缩命令有 gzip 和 zip
    SQL 常用的命令
    JVM内存管理的机制
    Linux 常见命令
  • 原文地址:https://www.cnblogs.com/cdp1591652208/p/7608707.html
Copyright © 2011-2022 走看看