大胖的部落格

Just a note

  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  112 随笔 :: 0 文章 :: 3 评论 :: 0 Trackbacks
一个类只能创建一个实例,提供一个全局访问点,用户不能随便创建对象。

1、构造函数私有可以保证用户不能创建对象。
2、提供public方法供用户访问对象,第一次访问时创建。
3、方法和数据为static类型,可以通过类名和域操作符调用成员函数。
4、提供销毁对象的public方法.
5、static成员在类外初始化。
#include <iostream>

using namespace std;


//Singleton
class Singleton
{
private:
    
static Singleton *s_pSingleton;

    Singleton()
    
{
        cout
<<"Constructor"<<endl;
    }


    
~Singleton()
    
{
        cout
<<"Destructor"<<endl;
    }


public:
    
static Singleton* Instance()
    
{
        
if(NULL == s_pSingleton)
        
{
            s_pSingleton 
= new Singleton();
        }

        
return s_pSingleton;
    }


    
static void Destroy()
    
{
        
if(NULL != s_pSingleton)
        
{
            delete s_pSingleton;
            s_pSingleton 
= NULL;
        }

    }

}
;

//Initialization
Singleton* Singleton::s_pSingleton = NULL;


int main()
{
    
//Test
    Singleton::Instance();
    Singleton::Instance();
    Singleton::Destroy();
    Singleton::Destroy();
    Singleton::Instance();
    Singleton::Destroy();
    
return 0;
}

posted on 2009-05-27 11:24 大胖 阅读(115) 评论(0)  编辑 收藏 引用 所属分类: Design Pattern

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理