如何为我的班级创建一个好的界面

How to create a good interface for my class?

本文关键字:一个 界面 我的 创建      更新时间:2023-10-16

我可以用来组织我的代码吗?

我使用C 。

  1. 我有一个基类命令
  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;
}

为什么,简单地,命令没有在派生类中实现的虚拟纯方法?这样的东西:

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