[转载]Singleton的一个基类实现

今天去面试一家游戏公司,笔试题有道叫做 设计并实现一个Singleton基类。以前没有认真考虑过这个问题,转载了一篇。

原文地址:http://blog.csdn.net/Blue_Light/archive/2008/07/13/2646266.aspx

在创建型模式中,有一种设计模式“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;

}

原文地址:https://www.cnblogs.com/Henrya2/p/1777598.html