2013-03-16 128 views
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 
     ... 
    } 
}; 
+2

'CreateNewDocument'和'OpenDocument'對我來說似乎是兩件非常不同的事情。這兩個我都認爲是高水平的。 – 2013-03-16 11:53:45

回答

1

我會作出這樣的「低級別」 CreateNewDocument()方法protectedprivate,因爲它似乎,它應該只從該類中的其他類成員或派生的人分別稱爲。

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 
    } 
}; 

如果這些方法真的在不同的實現水平,可以考慮把它們分成不同的類或命名空間,作爲已經建議。使用必須實現純虛擬受保護成員函數的子類,您已經具有適當的封裝。