我正在寻找将对象分派到正确的“目标”对象的最佳方法。
我有一个基本的命令类: Cmd,两个子类: BufferCmd和StateCmd。命令"GotoLine“源自BufferCmd,"ChangeCmd”源自StateCmd。BufferCmds是用来访问Buffer类的,StateCmds是用来访问State对象的。
我目前设置了一个访问者模式,这样我就可以执行以下操作:
Buffer buffer;
State state;
Cmd *c;
GotoLineCmd gotoCmd = new GotoLineCmd (15);
ChangeCmd changeCmd = new ChangeCommand (...)
c = &gotoCmd;
c->accept (buffer);
c = &changeCmd;
c->accept (state);我想使用访问者模式,因为我希望能够做一些大致如下的事情:
Cmd *cmds [5];
cmds [0] = new GotoLineCmd (...);
cmds [1] = new CopyLineCmd (...);
cmds [2] = new PasteCmd (...);
foreach (Cmd *c in cmds) {
c->accept (buffer);
}不幸的是,为了使用它,我需要知道发送命令到哪个对象。我希望能够做这样的事情:
Derive Buffer from Commandable
Derive State from Commandable
Commandables *commandables [1] = {new Buffer (), new State () };
// Then have the foreach type statement look like:
foreach (Cmd *c in cmds) {
c->accept (commandables);
}有没有最适合这种情况的模式?我应该使用访问者模式吗?很明显,我想要避免这种情况:
foreach (Cmd *c in cmds) {
foreach (Commandable *cmdAbles in commandables) {
if (c->accept (commandables)) {
// Okay command accepted...
break;
}
}
}谢谢
发布于 2009-12-16 04:30:52
听起来更像是您想要名称恰当的Command pattern。
关键是将accept()的不同参数移到从Cmd派生的每个类的构造函数中。例如,GotoLineCommand的构造函数将行和缓冲区对象作为其构造函数的参数,并存储指向缓冲区对象的指针或引用。
完成此操作后,就不再需要accept()的参数,并且从Cmd派生的所有类的接口都是相同的
class Buffer
{
public:
void gotoLine(int line);
};
class Cmd
{
public:
virtual void accept() = 0;
};
class GotoLineCommand: public Cmd
{
public:
GotoLineCommand(Buffer & buffer, int line) :
buffer_(buffer),
line_(line)
{
}
virtual void accept()
{
buffer_.gotoLine(line_);
}
private:
Buffer & buffer_;
int line_;
};https://stackoverflow.com/questions/1910121
复制相似问题