基本概念
单例模式是一种创建型模式,一般的设计模式考察的比较常见。
核心思想是保证一个类只有一个实例并同一个全局访问点来访问这个实例。
基本要求
所有单例的实现都包含以下两个相同的步骤:
- 将默认构造函数设为私有, 防止其他对象使用单例类的
new
运算符。 - 新建一个静态构建方法作为构造函数。 该函数会 “偷偷” 调用私有构造函数来创建对象, 并将其保存在一个静态成员变量中。 此后所有对于该函数的调用都将返回这一缓存对象。
如果你的代码能够访问单例类, 那它就能调用单例类的静态方法。 无论何时调用该方法, 它总是会返回相同的对象。
创建方式
有两种创建方式,一种饿汉式,一种懒汉式
饿汉式就是在类加载时就已经完成了实例的创建,即不管后面创建的实例有没有使用,先创建再说,即饿得不行直接干。
而懒汉式则采用了懒加载的思路,只有在首次亲够实例的时候才创建,如果已经创建,返回已有的实例,即按需分配。
基本代码
/*** The Singleton class defines the `GetInstance` method that serves as an* alternative to constructor and lets clients access the same instance of this* class over and over.*/
class Singleton
{/*** The Singleton's constructor/destructor should always be private to* prevent direct construction/desctruction calls with the `new`/`delete`* operator.*/
private:static Singleton * pinstance_;static std::mutex mutex_;protected:Singleton(const std::string value): value_(value){}~Singleton() {}std::string value_;public:/*** Singletons should not be cloneable.*/Singleton(Singleton &other) = delete;/*** Singletons should not be assignable.*/void operator=(const Singleton &) = delete;/*** This is the static method that controls the access to the singleton* instance. On the first run, it creates a singleton object and places it* into the static field. On subsequent runs, it returns the client existing* object stored in the static field.*/static Singleton *GetInstance(const std::string& value);/*** Finally, any singleton should define some business logic, which can be* executed on its instance.*/void SomeBusinessLogic(){// ...}std::string value() const{return value_;}
};/*** Static methods should be defined outside the class.*/Singleton* Singleton::pinstance_{nullptr};
std::mutex Singleton::mutex_;/*** The first time we call GetInstance we will lock the storage location* and then we make sure again that the variable is null and then we* set the value. RU:*/
Singleton *Singleton::GetInstance(const std::string& value)
{std::lock_guard<std::mutex> lock(mutex_);if (pinstance_ == nullptr){pinstance_ = new Singleton(value);}return pinstance_;
}void ThreadFoo(){// Following code emulates slow initialization.std::this_thread::sleep_for(std::chrono::milliseconds(1000));Singleton* singleton = Singleton::GetInstance("FOO");std::cout << singleton->value() << "\n";
}void ThreadBar(){// Following code emulates slow initialization.std::this_thread::sleep_for(std::chrono::milliseconds(1000));Singleton* singleton = Singleton::GetInstance("BAR");std::cout << singleton->value() << "\n";
}int main()
{ std::cout <<"If you see the same value, then singleton was reused (yay!\n" <<"If you see different values, then 2 singletons were created (booo!!)\n\n" <<"RESULT:\n"; std::thread t1(ThreadFoo);std::thread t2(ThreadBar);t1.join();t2.join();return 0;
}
If you see the same value, then singleton was reused (yay!
If you see different values, then 2 singletons were created (booo!!)RESULT:
FOO
FOO
上述实例中,使用了多线程去模拟创建单例,其中我们使用了lock_guard
的库函数,该函数接受一个mutex
变量,使用互斥锁同步阻塞,且无需手动解锁。这样确保在任何时刻只有一个线程能够执行实例的创建。由于Foo
线程先创建,所以该实例输出两行FOO
单例模式的用途
- 资源共享:多个模块共享某一个资源,比如应用程序需要一个全局的配置管理器,或者是数据库连接池
- 只有一个实例:当系统中只需要一个实例来协调行为的时候,比如管理应用程序中的缓存,确保只有一个缓存实例,或者创建和管理一个线程池
- 懒加载:如果对象创建本省就比较消耗资源,而且可能在整个程序中都不一定会使用,可以使用单例模式来懒加载。
实际举例如下
- Web项目中的配置对象的读取。
- 数据库连接池。
- 多线程池。
单例模式的优缺点
优点:全局控制,节省资源,懒加载
缺点:
- 该模式同时解决了两个问题,控制类实例化的过程和提供全局访问点。这就使得单例类既要承担创建对象的职责,又要承担提供访问对象的职责,违背了单一职责原则。
- 可能会造成线程安全问题。