单例模式

什么是单例模式:

在GOF的《设计模式:可复用面向对象软件的基础》中是这样说的:保证一个类只有一个实例,并提供一个访问它的全局访问点。

如何保证?

  1. 首先,需要保证一个类只有一个实例,那么就要在类中,要构造一个实例,就必须调用类的构造函数,如此,为了防止在外部调用类的构造函数而构造实例,需要将构造函数的访问权限标记为protected或private;

  2. 最后,需要提供要给全局访问点,就需要在类中定义一个static函数,返回在类内部唯一构造的实例。

#include <iostream>
using namespace std;
class Singleton {
public:
    static Singleton * getinstance() {
        if (p == NULL) {
            p = new Singleton();
        }
        else {
            return p;
        }
    }
    int gettest() {
        return test;
    }
    void settest(int _t) {
        test = _t;
    }
private:
    Singleton() { test = 0; }
    static Singleton * p;
    int test;
};
Singleton * Singleton::p = NULL;
int main() {
    Singleton *p = Singleton::getinstance();
    cout << p->gettest() << endl;
    system("pause");
    return 0;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容