zoukankan      html  css  js  c++  java
  • C++如何设计只实例化一次的类?

    这是在看侯捷C++视频的时候,他提出的一个问题,称之为单例模式(singleton),有两种实现方式(懒汉与饿汉),还有多线程,使用场景(工厂模式)等等一些相关的东西,更多了解可以去百度一下。在此就简单做一个总结。

    方法一共有n个。根据侯老师所言,目前这两种是比较好的实现方式,所以找出来与大家分享一下。一是:

    #include<iostream>
    #include<vector>
    #include<string>
    using namespace std;
    class A{
    public:
        static A& getObject() {
            return a ;
        }
        void set(int t){
            temp = t ;
        }
        void print(){
            cout << "temp == "<< temp << endl ;
        }
        //其他成员函数
    private:
        A() = default  ;
        A(const A& rhs);
        static A a ;
        int temp ;
    };
    A A::a ;
    int main(void){
        A::getObject().set(666);
        A::getObject().print();
        return 0 ;
    }
    

    运行结果:

    这里写图片描述

    另外还有下面的这种设计模式。相较于上面的,它就是只要用到就实例化出来,不用到就不浪费内存空间。

    #include<iostream>
    #include<vector>
    #include<string>
    using namespace std;
    class A{
    public:
        static A& getObject() { //给外界的唯一接口
            static A a ; //staic 离开函数仍然存在
            return a ;
        }
        void set(int t){
            temp = t ;
        }
        void print(){
            cout << "temp == "<< temp << endl ;
        }
        //其他成员函数
    private:
        A() = default ;
        A(const A& rhs) ;
        int temp ;
    };
    int main(void){
        A::getObject().set(45); //调用形式
        A::getObject().print();
        return 0 ;
    }

    运行结果:

    这里写图片描述

    当然了,使用new实现也是完全可以的。但是我觉得不是很建议。

    #include<iostream>
    #include<vector>
    #include<string>
    using namespace std;
    class A{
    public:
        static A* getObject();
        void set(int t){
            temp = t ;
        }
        void print(){
            cout << "temp == "<< temp << endl ;
        }
        //其他成员函数
    private:
        A() = default ;
        A(const A& rhs) ;
        ~A(){   //析构函数即使在private中还是会自动执行,不用再写public函数 delete
            delete p_A ;
        }
        A& operator=(const A&); //把复制构造函数和=操作符也设为私有,防止被复制
    
        static A *p_A ;
        int temp ;
    };
    //注意初始化!!!
    A* A::p_A = new A();
    A* A::getObject(){
        return p_A;
    }
    
    int main(void){
        A* A1 = A::getObject();
        A* A2 = A::getObject();
    
        if (A1 == A2)
            fprintf(stderr,"A1 = A2
    ");
    
        A1->set(888);
        A1->print();
    
        return 0;
    }

    运行结果:

    这里写图片描述

  • 相关阅读:
    懒加载与预加载
    Javascript之 Ajax 与 JSON
    Q&A:为什么prototype中的方法不能赋值给变量,再调用?
    Javascript之 浅克隆 与 深克隆
    Javascript之 __proto__ 与 prototype
    React入门(二)—— Props属性
    React入门(一)—— State属性
    Flask调用layer-iframe后,如何从服务器端关闭弹出窗
    Python从入门到项目实践(明日科技 吉林大学出版社)
    从实例到数理来解析感知机学习算法(PLA)
  • 原文地址:https://www.cnblogs.com/Tattoo-Welkin/p/10335305.html
Copyright © 2011-2022 走看看