zoukankan      html  css  js  c++  java
  • Singleton模式——设计模式学习

          Singleton

    一 意图

      保证一个类仅有一个实例,并提供一个访问的全局访问点。

    二 结构

           为什么需要仅有一个类的单例类呢?在很多种情况下,一个系统只需要此类的一个实例就够了:一个窗口管理器,一个消息通知器,一个数据存储器……

           有时候只能有一个:系统共用一个存储器,很多地方访问到存储器,必须要保证存储器唯一。

    三 代码实现

    class Singleton
    {
    protected:
    Singleton()
    {
    cout<<"Singleton constructor"<<endl;
    }
    public:
    static Singleton* getInstance()
    {
    if (s_instance == NULL)
    {
    new Singleton();
    }
    return s_instance;
    }
    static closeIstance()
    {
    if (s_instance != NULL)
    {
    delete s_instance;
    s_instance = NULL;
    }
    }
    private:
    static Singleton* s_instance;
    };
    Singleton* Singleton::s_instance = NULL;
    int main()
    {
    Singleton* single = Singleton::getInstance();
    return 0;
    };

    从结构上来看是看起来非常的简单,因为这仅仅是对类的使用方式进行了限制,使对类实例创建得到更容易控制。


    四 实例分析

           事件通知栏实现:

      

    平台上单例类的实现方式:

    两个宏

    1 声明

    #define VFX_OBJ_DECLARE_SINGLETON_CLASS(_className)                             \
    public: \
    static _className *getInstance(); \
    static void closeInstance(); \
    private: \
    static VfxU8 s_InstanceBuf[]; \
    static _className *s_instance

    2 实现

    #define VFX_OBJ_IMPLEMENT_SINGLETON_CLASS(_className)                           \
    _className *_className::getInstance() \
    { \
    if (s_instance == NULL) \
    { \
    new (s_InstanceBuf) _className(); \
    s_instance = (_className *)s_InstanceBuf; \
    s_instance->init(NULL); \
    } \
    return s_instance; \
    } \
    \
    void _className::closeInstance() \
    { \
    if (s_instance != NULL) \
    { \
    s_instance->deinit(); \
    s_instance = NULL; \
    } \
    } \
    \
    VfxU8 _className::s_InstanceBuf[sizeof(_className)]; \
    _className *_className::s_instance = NULL
  • 相关阅读:
    JS站点
    1011 World Cup Betting (20分)
    1007 Maximum Subsequence Sum (25分)(动态规划DP)
    1006 Sign In and Sign Out (25分)
    1005 Spell It Right (20分)
    1004 Counting Leaves (30分)(DFS)
    1003 Emergency (25分)(Dijkstra算法)
    1002 A+B for Polynomials (25分)
    1001 A+B Format (20分)
    canvas
  • 原文地址:https://www.cnblogs.com/bastard/p/2312419.html
Copyright © 2011-2022 走看看