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;

    }

  • 相关阅读:
    java 读取配置文件
    oracle sql 截取表中某一字段的部分作为该字段查询结果
    大数据课堂
    网站保存
    Tensorflow+Keras 深度学习人工智能实践应用 Chapter Two 深度学习原理
    Tensorflow+Keras 深度学习人工智能实践应用 Chapter One人工智能 机器学习与深度学习简介
    Python 机器学习及实践 Coding 无监督学习经典模型 数据聚类 and 特征降维
    博客地址的保存
    备注
    个人笔记-
  • 原文地址:https://www.cnblogs.com/Henrya2/p/1777598.html
Copyright © 2011-2022 走看看