单件模式,是允许一个类有且仅有一个实例的方法。
#include <iostream> using namespace std; class Singleton { static Singleton s; // 创建静态对象 int i; Singleton(int x) : i(x) { } // 禁止构造函数 Singleton(const Singleton&); // 禁止复制构造函数 Singleton& operator=(Singleton&); // 禁止赋值 public: static Singleton& instance() { return s; } // 返回对象的引用 int getValue() { return i; } void setValue(int x) { i = x; } }; Singleton Singleton::s(47); int main() { Singleton& s = Singleton::instance(); cout << s.getValue() << endl; Singleton& s2 = Singleton::instance(); s2.setValue(9); cout << s.getValue() << endl; }
选自《C++编程思想》。