【设计模式】C++单例模式

实现单例的步骤

  1. 构造函数私有化。不能让外部访问构造函数。
  2. 增加静态私有的当前类的指针变量。
  3. 提供静态对外接口,可以让用户获得单例对象。

单例划分:1.懒汉式 2.饿汉式

//懒汉式,需要的时候再创建
class Singleton_lazy {
private:
	Singleton_lazy() {}
	static Singleton_lazy* getInstance() {
		if (pSingleton == NULL) {
			pSingleton = new Singleton_lazy;
		}
		return pSingleton;
	}
private:
	static Singleton_lazy* pSingleton;
};
//类外初始化
Singleton_lazy* Singleton_lazy::pSingleton = NULL;
//饿汉式,在main函数之前创建
class Singleton_hungry {
private:
	Singleton_hungry() {}
	static Singleton_hungry* getInstance() {
		return pSingleton;
	}
private:
	static Singleton_hungry* pSingleton;
};
//类外初始化
Singleton_hungry* Singleton_hungry::pSingleton = new Singleton_hungry;
posted @ 2020-06-24 17:10  ninding  阅读(115)  评论(0编辑  收藏  举报