2017-08-31 61 views
-2

有什麼好的開發模式可以用來組織我的代碼?如何爲我的班級創建一個好的界面?

我使用C++。

  1. 我有一個基類命令的從命令類
  2. 類事務處理,其存儲命令的陣列(可改變)

隨着當前的方法的用戶派生類

  • 數十交易界面應該做類似

    template <typename Base, typename T> 
        inline bool instanceof(const T *ptr) { 
        return typeid(Base) == typeid(*ptr); 
        } 
    
    Transaction tx; 
    
    // here I want to process all commands 
    for(int i=0; i < N; i++){ 
        if(instanceof<AddPeer>(tx.get(i)) { 
        // ... process 
        } 
        if(instanceof<TransferAsset>(tx.get(i)) { 
        // ... process 
        } 
        ... for every type of command, but I have dozens of them 
    } 
    

    class Command; 
    class TransferAsset: public Command {} 
    class AddPeer: public Command {} 
    // dozens of command types 
    
    class Transaction{ 
    public: 
        // get i-th command 
        Command& get(int i) { return c[i]; } 
    private: 
        // arbitrary collection (of commands) 
        std::vector<Command> c; 
    } 
    
  • 回答

    1

    爲什麼,簡單地說,Command沒有一個虛擬的純粹的方法來實現派生類? 事情是這樣的:

    class Command 
    { virtual void process() =0;}; 
    class TransferAsset: public Command 
    { 
        void process() 
        { 
        //do something 
        } 
    }; 
    class AddPeer: public Command  
    { 
        void process() 
        { 
        //do something 
        } 
    }; 
    

    你的代碼可能是然後:

    Transaction tx; 
    // here I want to process all commands 
    for(int i=0; i < N; i++) 
    { 
        tx.get(i)->process(); 
    } 
    
    +0

    如果命令的處理是硬(大量的代碼),那麼它可能是壞的,直接給這個處理邏輯'過程「方法。我正在考慮'class Processor',它將被傳遞給'void process(Processor&e)'。這是好的設計嗎? – warchantua

    相關問題