使用场景:
整个系统中只允许有一个实例,例如:调度程序,某些特殊服务等。
实现方法:
将构造函数设置为private或者protected,然后设置一个静态方法(为什么必须要静态?因为无法new出一个对象来),供其他函数访问这个唯一的实例。
代码:
#include <iostream> using namespace std; class Singleton { protected: Singleton(){}; public: static Singleton * getInstance() { if(_instance==0) { _instance = new Singleton(); } return _instance; } ///other class functions... void show() { cout<<"This is a Singleton !"<<endl; } private: static Singleton * _instance; ///other class members ... }; ///静态成员的初始化方法 Singleton * Singleton::_instance = 0; int main() { Singleton *s=Singleton::getInstance(); s->show(); return 0; }
单例模式应该是设计模式中最简单的一个吧~
下一个:工厂模式。