工厂模式克隆保护基类的成员

时间:2014-12-26 05:58:53

标签: c++ factory

这是一个设计问题。

我需要根据 Base 类对象创建派生类的对象。但基础的受保护成员显然无法通过基础类指针在派生中访问...

有没有一种很好的方法来解决这个混乱,而不必将派生类声明为基类的朋友?

class ProtectedImpl;

class Base
{
    //friend class Derived; //this solves the problem, but...
    public:
    static Base* create()
    {
        Base* base = new Base;
        // init impl here...
        return base;
    }

    protected:
    ProtectedImpl* impl;
};

class Derived: public Base
{
    public:
    static Derived* create()
    {
        Derived * derived = new Derived;
        // init impl here...
        return derived;
    }

    static Derived* clone(Derived* d)
    {
        Derived* derived = new Derived;
        ProtectedImpl* impl = d->impl; // OK!
        //derived->impl = ... // clone implementation here
        return derived;
    }

    /* This doesn't work 
    static Derived* clone(Base* b)
    {
        Derived* derived = new Derived;
        ProtectedImpl* impl = b->impl; // impl can't be accessed with a Base pointer
        //derived->impl = ... // clone implementation here
        return derived;
    }
    */
};

1 个答案:

答案 0 :(得分:0)

为什么不在基类中引入一个setter,如:

class Base {
    ....
protected:
    virtual void setImpl(ProtectedImpl *pImpl) {
         // check validity of pImpl here
         impl = pImpl;
    }
}

然后您可以在Derived类中使用它,并在必要时覆盖默认实现。 但是,你的静态create()函数已经创建了一个实现,所以如果你想调用它,你也需要处理它,可能还有这个setter的版本用现有的实现替换另一个,或者通过mofying创建()所以它接受一个指向实现的指针,默认值为NULL,如果它不是NULL,则使用该参数。