• [转载]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;

    }

  • 相关阅读:
    css3实现轮播2
    css3实现轮播1
    读阮一峰ES6笔记4:字符串的新增方法
    读阮一峰ES6笔记3:字符串的扩展
    应用流策略与检查配置结果
    配置流策略
    配置流行为
    配置流分类
    "流量监管"和"流量整形"的区别
    802.1p 优先级与内部优先级的映射关系
  • 原文地址:https://www.cnblogs.com/Henrya2/p/1777598.html
Copyright © 2020-2023  润新知