如何为我的 class 创建一个好的界面?

How to create a good interface for my class?

有什么好的开发模式可以用来组织我的代码吗?

我使用 C++。

  1. 我有一个基地 class 命令
  2. 从命令 class
  3. 派生的数十个 classes
  4. class事务,存储命令数组(可更改)

使用当前方法,事务接口的用户应该做类似

的事情
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;
}

为什么简单地说,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();
}