【问题标题】:Return objec of derived class whose base is singleton返回基为单例的派生类的对象
【发布时间】:2013-03-20 06:12:51
【问题描述】:

如何返回对象或调用基类为单例的派生类的getInstance

【问题讨论】:

  • 虽然可以通过 hacks/cracks 来实现。最好改变设计,因为这个要求似乎不自然。
  • 我同意@iammilind - 需要这样的东西吗?

标签: c++ visual-c++


【解决方案1】:

您必须使用 C++ 中不支持的虚拟静态方法(据我所知,它在 Delphi 中受支持 - 有点好奇)。

您必须决定,两个类或每个类只有一个实例(例如,如果您通过 GetInstance 创建一个 Derived 实例,您是否能够创建 Base 实例)。

在这些类中没有办法解决这个问题,你必须创建一个类工厂。类似的东西(我已经省略了单例实现以使想法更清晰 - 显然你知道如何实现)

class SingletonFactory
{
    template<typename T>
    static T * GetInstance()
    {
        return T.GetInstance();
    }
};

class Base
{
    friend class SingletonFactory;

private:
    static Base * GetInstance()
    {
        // ...
    }

protected:
    Base()
    {
    }
};

class Derived : public Base
{
    friend class SingletonFactory;

private:
    static Derived * GetInstance()
    {
    }

protected:
    Derived()
        : Base()
    {
    }
};

// (...)

Derived * d = SingletonFactory::GetInstance<Derived>();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-20
    • 1970-01-01
    • 2014-01-01
    • 1970-01-01
    • 2018-10-19
    相关资源
    最近更新 更多