看单例模式的例子:
运行结果:
可见调用两次instance()只调用了一次构造函数,只产生了一个对象,指针clienta和clientb存储的是同一个对象的地址。这就是单例模式,通过将类的构造函数设为private,保证只能有一个对象存在。
-
C/C++ code
-
#include < iostream > class Singleton{ private : Singleton( int i = 0 ):val(i){ // 构造函数私有 std::cout << " constructor,member val = " << val << std::endl; } int val; static Singleton * ins; public : static Singleton * instance(){ // 工厂方法 return ins; } int getVal(){ return val; } void setVal( int i){ val = i; } virtual ~ Singleton(){ if (ins){ delete ins; std::cout << " destructor " << std::endl; } } }; Singleton * Singleton::ins = new Singleton( 10 ); int main(){ Singleton * clienta = Singleton::instance(); Singleton * clientb = Singleton::instance(); std::cout << " adress clienta: " << clienta << std::endl; std::cout << " adress clientb: " << clientb << std::endl; return 0 ; }
运行结果:
-
Perl code
-
$ g++ -Wall singleton.cpp -o singleton $ ./singleton constructor,member val = 10 adress clienta: 0x804a008 adress clientb: 0x804a008
可见调用两次instance()只调用了一次构造函数,只产生了一个对象,指针clienta和clientb存储的是同一个对象的地址。这就是单例模式,通过将类的构造函数设为private,保证只能有一个对象存在。