一、题目

设计一个类,我们只能生成该类的一个实例

二、思路

单例模式是一种软件设计模式,表示单例对象设计的类只能允许一个实例存在。

单例模式的基本解题思路为:

  1. 将类的构造函数设为私有,外部无法直接通过默认构造函数来生成新的实例,只提供一个公共的静态接口函数返回该实例。
  2. 当外部没有引用当前实例时,创建并返回该实例。如果该实例已经存在了,直接返回。

单例模式共有两种实现方法:

  1. 饿汉模式:饿汉是指在实例初始化时就创建好,后面直接使用。
  2. 懒汉模式:懒汉模式是实例在使用了,万不得已的情况下才创建。

三、饿汉模式实现

#include <iostream>
using namespace std;

class CSingleTon {
private:
    CSingleTon() {
        cout << "CSingleTon" << endl;
    }

    static CSingleTon *instance;
public:
    static CSingleTon *getInstance() {
        return instance;
    }
    static void destoryInstance() {
        if (instance != NULL) {
            delete instance;
            instance = NULL;
        }
    }
};

CSingleTon *CSingleTon::instance = new CSingleTon();

int main() {
    cout << "helloworld" << endl;

    CSingleTon *s1 = CSingleTon::getInstance();
    CSingleTon *s2 = CSingleTon::getInstance();
    CSingleTon *s3 = CSingleTon::getInstance();

    cout << s1 << "\n"
        << s2 << "\n"
        << s3 << endl;

    s1->destoryInstance();

    return 0;
}

编译运行:

注意:CSingleTon是在helloworld的前面打印出来的,说明程序在创建时就已经生成了实例。并且三个实例的地址都是相同的。

四、懒汉模式实现

#include <iostream>

using namespace std;

class CSingleTon {
private:
    CSingleTon() {
        cout << "CSingleTon" << endl;
    }

    static CSingleTon *instance;
public:
    static CSingleTon *getInstance() {
        if (instance == NULL) {
            instance = new CSingleTon();
        }
        return instance;
    }
    static void destoryInstance() {
        if (instance != NULL) {
            delete instance;
            instance = NULL;
        }
    }
};

CSingleTon *CSingleTon::instance = NULL;

int main() {
    cout << "helloworld" << endl;

    CSingleTon *s1 = CSingleTon::getInstance();
    CSingleTon *s2 = CSingleTon::getInstance();
    CSingleTon *s3 = CSingleTon::getInstance();

    cout << s1 << "\n"
        << s2 << "\n"
        << s3 << endl;

    s1->destoryInstance();

    return 0;
}

编译运行,和上面的不同,helloworld先打印出来了,并且三个实例的地址也都是相同的:

最后修改:2019 年 04 月 17 日
如果觉得我的文章对你有用,请随意赞赏