我如何使用接口隐藏我的实现,并且仍然使用继承构建类



我喜欢使用接口来隐藏我的实现细节的想法。我也非常喜欢使用继承作为在我以前创建的类的基础上构建的一种方式。如何使这两个好处共存?这是我的问题的一个例子:

object.h
class object {
    protected:
        //stuff that should be available to derived classes
        virtual void    derivedHelper    () = 0;
    public:
        //stuff that should be available to the client
        virtual object* create           () = 0;
        virtual void    mainTask         () = 0;
}
object.cpp
class objectPriv : public object {
    private:
        //implementation specific details and members
    protected:
        void derivedHelper () {
             //some stuff
        }
    public:
        objectPriv() { }
        object* create () {
            return(new objectPriv());
        }
        void mainTask () {
            //more stuff
        }
}
superObject.h
class superObject : public object {             //problem #1
    public:
        //stuff that should be available to the client
        virtual superObject* create  () = 0;
}
superObject.cpp
class superObjectPriv : public superObject {    //problem #2
    private:
        //the magic behind super object
    public:
        superObjectPriv() { }
        superObject* create () {
            return(new superObjectPriv());
        }
        void mainTask () {
            object::mainTask();                 //problem #3
            object::derivedHelper();            //problem #4
            //super extra stuff
        }
}

所以你可以在这里看到这不会编译。

我可以为 superObject 实现对象的纯虚拟,但这违背了从对象派生的目的。我不想复制实现,我想在此基础上构建。

我可以更改 superObject 以从 objectPriv 派生,但随后我将公开我的实现细节。我想向所有人隐藏有关对象Priv的所有具体内容。

我想不出任何方法来实现这一点。我有一种不好的预感,这可能是不可能的,但我的手指交叉,你们会为我提供一些聪明的技巧:)

谢谢莱斯

你考虑过混合模式吗? 这是一种将共享实现添加到多个类的方法。 一个定义一个从它的参数派生的模板类。 你可以用 ObjectPriv 和 SuperObjectPriv 的常见行为来做到这一点:

template <typename ParentT>
class CommonFunctionalityMixin
: public ParentT   // this is the magic line that makes it a mixin
{
    public:
        typedef ParentT parent_type;
        virtual void mainTask()      { /* implementation */ }
        virtual void derivedHelper() { /* implementation */ }
};
class ObjectPriv
: public CommonFunctionalityMixin<object> // which derives from object
{
    public:
        typedef CommonFunctionalityMixin<object> parent_type;
        virtual object* create()     { return new ObjectPriv; }
        // virtual void mainTask() defined in CommonFunctionalityMixin
        // virtual void derivedHelper() defined in CommonFunctionalityMixin
};
class SuperObjectPriv
: public CommonFunctionalityMixin<superObject> // which derives from superObject
{
    public:
        typedef CommonFunctionalityMixin<object> parent_type;
        virtual object* create()     { return new SuperObjectPriv; }
        // now we override CommonFunctionalityMixin's mainTask() with super's
        virtual void mainTask()
        {
            parent_type::mainTask();
            parent_type::derivedHelper();
        }
};

最新更新