Singleton的一个基类实现

    在创建型模式中,有一种设计模式“Singleton”。该模式的意图是,保证一个类仅有一个实例,并提供一个访问它的全局访问点。在GOF的指导下,我们经常写一些Singleton类。每个类很类似。

   以下代码描述了一个Singleton的基类及使用方法:

template <class T>

class AllocUsingNew

{

public:

    static T* Create()

    {

       return new T;

    }

 

    static void Destroy(T *p)

    {

       delete p;

    }

};

 

template <class T>

class AllocUsingStatic

{

public:

    static T* Create()

    {

       static T t;

       return new (&t)T;

    }

 

    static void Destroy(T *p)

    {

       p->~T();

    }

};

 

template <class T,template <class> class AllocPolicy = AllocUsingStatic>

class Singleton

{

public:

    static T* Instance()

    {

       if (NULL == m_pThis)

       {

           m_pThis = AllocPolicy<T>::Create();

           assert(m_pThis);

           m_pThis->Initialize();

       }

       return m_pThis;

    }

 

    static void Destroy()

    {

       if (m_pThis)

       {

           m_pThis->Finalize();

           AllocPolicy<T>::Destroy(m_pThis);

           m_pThis = NULL;

       }

    }

 

    void Initialize()

    {

    }

 

    void Finalize()

    {

    }

 

protected:

    Singleton(){}

    ~Singleton(){}

private:

    Singleton(const Singleton&);

    Singleton& operator = (const Singleton&);

    friend class AllocPolicy<T>;

private:

    static T * m_pThis;

};

 

template <class T,template <class> class AllocPolicy>

T* Singleton<T,AllocPolicy>::m_pThis = NULL;

 

class MySingleton : public Singleton<MySingleton,AllocUsingNew>

{

public:

    void SetValue(int value)

    {

       m_value = value;

    }

 

    void print()

    {

       cout << m_value << endl;

    }

 

    void Initialize()

    {

       m_value = 1000;

    }

 

private:

    int m_value;

};

 

 

int _tmain(int argc, _TCHAR* argv[])

{

    MySingleton::Instance()->print();

    MySingleton::Destroy();

 

    system("pause");

 

    return 0;

}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值