2017-08-31 8 views
-2

私のコードを整理するのに使える良い開発パターンはありますか?私のクラスのための良いインターフェイスを作成するには?

私はC++を使用しています。現在のアプローチで

  1. Iは、基本クラスのコマンドをコマンドのアレイを記憶
  2. クラストランザクションは、(変更可能)コマンド・クラスから派生したクラスの
  3. 数十を有する

ユーザのトランザクションインタフェースのような何かを行う必要があります

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

単純に、派生クラスに実装する仮想純粋なメソッドがないのはなぜですか?このような 何か:

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

関連する問題