单例模式
单线程
保证类仅有一个实例,并提供一个访问它的全局访问点。
- 构造函数私有化,避免外界使用new来创造实例
- 通过判断一个局部static变量来确定是否创造实例
- 通过接口
GetInstance
来取得实例class Singleton { private: static Singleton instance; private: Singleton(){...} public: static Singleton GetInstance() { if(instance==null) { instance = new Singleton(); } return instance; } };
多线程
多个线程同时访问Singleton类是可能创造多个实例的。 - 通过对临界区加锁来避免多个线程同时访问
GetInstance
- 避免加锁开销过大,进行优化,只有实例未被创建时再加锁
class Singleton { private: static Singleton instance; static readonly obj sync = new obj(); private: Singleton(){...} public: static Singleton GetInstance() { if(instance==null) { lock(sync) { if(instance==null) instance = new Singleton(); } } return instance; } };
饿汉模式和懒汉模式
饿汉模式:用静态初始化的方式,类一加载就实例化的对象,提前占用系统资源,但不需要加锁;
懒汉模式:第一次被引用时才会将自己实例化,但是存在线程安全问题,需要加锁。
饿汉模式通过阻止派生,初始化就创建实例来实现。
简单工厂模式
用一个单独的类来做创造实例的过程。如一个计算器的实现。