使用单件构造器(SingletonConstructor)顺序初始化单件

使用单件构造器(SingletonConstructor)保证单件顺序初始化

对于单件模式时,目前主要有两种方法,即静态初始化以及动态初始化
对于动态初始化,由于锁(Double Check Lock)的加入,必然无法应用于高性能要求的场合。
对于静态初始化,单件的初始化顺序是不能保证的,如果单件直接存在依赖关系,这将导致初始化失败。
为了解决这个问题,引入一个单件构造器,由单件构造器来负责对各个单件进行显式的初始化

单件构造器(SingletonConstructor)定义如下:
1.单件构造器是所有其他单件的友元。
2.单件构造器是所影响域存在的唯一的静态初始化单件。

//Head file
class SingletonConstructor{
private:
    SingletonConstructor();
    ~SingletonConstructor();
    SingletonConstructor(SingletonConstructor const&);
    SingletonConstructor& operator=(SingletonConstructor const&);

    static SingletonConstructor s_SingletonConstructor_;
};

calss SingletonA{
public:
    friend class SingletonConstructor;
    SingletonA& Instance()
    {
        return *s_SingletonA_;
    }
private:
    SingletonA()
    {
        if (!s_SingletonA_)
            s_SingletonA_ = this;
    }

    ~SingletonA();
    SingletonA(SingletonA const&);
    SingletonA& operator=(SingletonA const&);

    static SingletonA *s_SingletonA_;
}

calss SingletonB{
public:
    friend class SingletonConstructor;
    SingletonB& Instance()
    {
        return *s_SingletonC_;
    }
private:
    SingletonB()
    {
        if (!s_SingletonB_)
        s_SingletonB_ = this;
    }
    ~SingletonB();
    SingletonB(SingletonB const&);
    SingletonB& operator=(SingletonB const&);
    
    static SingletonB *s_SingletonB_;
}

calss SingletonC{
public:
    friend class SingletonConstructor;
    SingletonC& Instance()
    {
    return *s_SingletonC_;
    }
private:
    SingletonC()
    {
        if (!s_SingletonB_)
        s_SingletonB_ = this;
    }
    ~SingletonC();
    SingletonC(SingletonC const&);
    SingletonC& operator=(SingletonC const&);
    static SingletonC *s_SingletonC_;
}

//Cpp file
SingletonConstructor SingletonConstructor::s_SingletonConstructor_;

SingletonConstructor::SingletonConstructor()
{
    m_SingleA = new SingletonA();
    m_SingleB = new SingletonB();
    m_SingleC = new SingletonC();
    //Or you can use std::vector<SingletonBase *> instead of m_Single*
}

SingletonConstructor::~SingletonConstructor()
{
    delete m_SingleC;
    delete m_SingleB;
    delete m_SingleA;
    //Or you can use std::vector<SingletonBase *> instead of m_Single*
}

单件构造器的思想在于显式初始化各个单件。

继续阅读 使用单件构造器(SingletonConstructor)顺序初始化单件