jlz

  C++博客 :: 首页 :: 联系 :: 聚合  :: 管理
  0 Posts :: 13 Stories :: 0 Comments :: 0 Trackbacks

常用链接

留言簿

我参与的团队

搜索

  •  

最新评论

   希望有且只有一个类的实列返回给调用程序时,就可以使用单元素模式(singleton pattern):

  class  TheOnlyInstance
{
public:
static TheOnlyInstance * GetTheOnlyInstance();

protected:
TheOnlyInstance(){}
};

通过 把构造函数声明为protected,并去掉公有构造。防止局部实例被创建。

TheOnlyInstance the; // not allowed

只能通过公有静态方法GetTheOnlyInstance 来访问类。
通过 把构造函数声明为protected,并去掉公有构造。防止局部实例被创建。

TheOnlyInstance *  TheOnlyInstance : GetTheOnlyInstance()
{
static TheOnlyInstance obj;
return &obj;
}

检索指向这个类的指针,只需要调用GetTheOnlyInstance()

TheOnlyInstance* pTheOnlyInstance = TheOnlyInstance: GetTheOnlyInstance();
posted on 2008-09-24 23:17 jz 阅读(69) 评论(0)  编辑 收藏 引用 所属分类: c++ primer plus 读书笔记