加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

单例模式

发布时间:2020-12-15 21:04:09 所属栏目:大数据 来源:网络整理
导读:看单例模式的例子: 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 *
看单例模式的例子:
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,保证只能有一个对象存在。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读