2017-08-31 62 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

    相关问题