zl程序教程

您现在的位置是:首页 >  其他

当前栏目

C++设计模式 - 单例模式

2023-03-20 15:01:26 时间

单例模式(Singleton)

介绍

单例模式是创建型设计模式,即用于创建对象的设计。其能够保证当前系统仅存在一个实例,并提供获取该实例的接口供客户端使用。(即创建对象禁止使用new,而是通过类的接口返回一个已经存在的对象。当强行new操作时,编译报错)

单例模式的实现较为简单,部分专家并不认为其是一种设计,而是一种编程技巧。

意义

既然存在单例模式,那么其存在的意义是什么呢?又或者说能解决什么问题?

  1. 减少对象多次创建与销毁,节省系统时间与资源。 通常局部代码使用对象时,通常临时创建,用完释放。若使用的对象占用资源很少,还看不出什么影响。假设是一个很庞大的类,其创建和销毁对象就会耗时且浪费资源。若多个任务都这么使用,统计起来也会是一笔没有必要的浪费。
  2. 保证系统资源被统一管理。 在系统资源共享的情况下,每个任务都可以随意使用当前 资源。如果想了解共享资源被哪些任务使用时,难以实现。若设计对共享资源进行管理的单例类,所有的任务都只能通过单例类来访问共享资源。就可以实现此种需求。

实现

在上述介绍中,已经大致描述了单例的特点:

  • 创建唯一的实例 。实现方法,将默认构造函数声明为私有,防止其他任务在外部使用new创建实例。
  • 提供获取实例的接口。实现方法,新建一个静态类成员函数,该函数能够调用构造函数来创建对象,并缓存到静态成员中并返回。其他任务通过此函数获取到的便都是同一个实例。

类图 单例模式

代码

#include <iostream>
#include <unistd.h>
#include <thread>

using namespace std;

class CSingleton
{
public:

    ~CSingleton() {}

    static CSingleton *getInstance(string value);

    string getValue()
    {
        return mValue;
    }

private:

    CSingleton(const string value): mValue(value)
    {
    }

    string mValue;
};

CSingleton* CSingleton::getInstance(string value)
{
    static CSingleton mObj(value);
    return &mObj;
}

void threadFirst()
{
    CSingleton* pSingleton = CSingleton::getInstance("first");
    cout << pSingleton->getValue() << "
";
}

void threadSecond()
{
    CSingleton* pSingleton = CSingleton::getInstance("second");
    cout << pSingleton->getValue() << "
";
}

void threadThird()
{
    CSingleton* pSingleton = CSingleton::getInstance("third");
    cout << pSingleton->getValue() << "
";
}

int main(int argc, char *argv[])
{
    thread t1(threadFirst);
    thread t2(threadSecond);
    thread t3(threadThird);
    t1.join();
    t2.join();
    t3.join();

    return 0;
}

输出:

third
third
third

在三个子线程创建实例时,分别向构造函数传入了"first"、"second"、"third",实际输出时都是"third"。说明三个线程使用的都为同一个实例。

总结

单例模式目前使用的较为流行,其实现方法也比较简单。当遇到需要管理公共资源时,可以采用单例模式。