zoukankan      html  css  js  c++  java
  • [转载]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;

    }

  • 相关阅读:
    迅为4412开发板实验Menuconfig_Kconfig(上)
    迅为IMX6ULL开发板Linux 4G通信实验
    迅为IMX6ULL开发板Linux RS232/485驱动实验(下)
    迅为4412开发板实验_Makefile编译(下)
    迅为IMX6Q开发板QtE5.7编译(上)
    迅为干货 | iTOP-4418/6818移植mt6620热点
    UDT源码剖析(十一)之SendQueue And RecvQueue
    UDT源码剖析(九)之CCC
    UDT源码剖析(十)之Channel
    UDT源码剖析(八)之Cache
  • 原文地址:https://www.cnblogs.com/Henrya2/p/1777598.html
Copyright © 2011-2022 走看看