2

例如,我有两个方法 CreateNewDocument 和 OpenDocument,它们在我的 GUI 代码中处于两个不同的级别。一个是低级别,它只是按照方法名称的含义进行操作;另一个是高级别,它将在执行所需工作之前检查现有文档可能未保存的情况。低级名称出现在高级代码中,因为它们被调用来实现高级方法。我的问题是如何区分它们以免混淆用户和读者?下面请细化图解代码。

class GuiClass
{
public:
    // Re-implement to tell me how to do the low-level create new document.
    virtual void LowLevelCreateNewDocument(); 

    // Then I do the high-level version for you.
    void HighLevelCreateNewDocument()
    {
        // Handle unsavings and blabla...
        ...
        // Then do the low-level version
        LowLevelCreateNewDocument();
        // Afterward operations
        ...
    }
};
4

1 回答 1

1

我会制作那个“低级”CreateNewDocument()方法,protected或者private,因为看起来,它应该只从该类中的其他类成员或派生的成员中调用。

class GuiClass
{
public:
    // Then I do the high-level version for you.
    void CreateNewDocument()
    {
        // Handle unsavings and blabla...
        ...
        // Then do the low-level version
        CreateNewDocumentInternal();
    }

protected:
    //pure virtual to enforce implementation within derived classes.
    //                                        |
    //                                        V
    virtual void CreateNewDocumentInternal() = 0; 
};

class GuiClassImpl : public GuiClass
{
protected:
    /*virtual*/ void CreateNewDocumentInternal()
    {
        //Do the low-level stuff here
    }
};

如果这些方法确实在不同的实现级别上,请考虑将它们放入不同的类或名称空间中,如前所述。对于必须实现纯虚拟的受保护成员函数的子类,您已经有了适当的封装。

于 2013-03-16T12:17:50.387 回答