您的位置:首页 > 编程语言 > C语言/C++

C++如何设计只实例化一次的类?

2018-02-25 13:44 281 查看

这是在看侯捷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\n");

A1->set(888);
A1->print();

return 0;
}


运行结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: