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 }
  • 相关阅读:
    跳跃表原理
    查看Oracle操作历史的试图
    【概念】为什么有时全表扫描比通过索引扫描效率更高
    oracle驱动表以及如何确定驱动表
    SpringBoot学习(三)-----配置Bean
    leetcode 面试题58
    leetcode 1365 有多少小于当前数字的数字
    leetcode 1342 将数字变成 0 的操作次数
    leetcode1313 解压缩编码列表
    leetcode 1071 字符串的最大公因子
  • 原文地址:https://www.cnblogs.com/cdp1591652208/p/7608707.html
Copyright © 2011-2022 走看看