我可以使用任何良好的开发模式来组织我的代码吗?
我使用C ++。
使用当前方法,Transaction接口的用户应该执行类似
的操作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;
}
答案 0 :(得分: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();
}