命令模式的意图是“将请求封装为对象,从而让您参数化具有不同请求的客户端 ...”有人可以解释具有不同请求的参数化客户端意味着什么吗?以及命令模式如何用不同的请求参数化客户端?
这方面的任何解释都将受到高度赞赏
答案 0 :(得分:1)
class ICommand
{
public:
virtual ~ICommand()
{}
virtual int InitCommand() = 0;
virtual int ExecuteCommand() = 0;
virtual int FinalizeCommand() = 0;
};
class CCommandProcessor
{
public:
virtual ~ICommandProcessor()
{}
int ProcessCommand(ICommand *_pCommand);
{
int iResult = _pCommand->InitCommand();
if(iResult == 0)
{
cout << "InitCommand Failed" << endl;
return 0;
}
iResult = _pCommand->ExecuteCommand();
if(iResult == 0)
{
cout << "ExecuteCommand Failed" << endl;
return 0;
}
iResult = _pCommand->FinalizeCommand();
if(iResult == 0)
{
cout << "FinalizeCommand Failed" << endl;
return 0;
}
return 1;
}
}
class CCopyDocumentCommand : public ICommand
{
private:
std::string m_szDocumentName;
std::string m_szSavePath;
public:
CCopyDocumentCommand(std::string _szDocumentName, std::_szSavePath)
{
m_szDocumentName = _szDocumentName;
m_szSavePath = _szSavePath;
}
virtual int InitCommand()
{
//check the document save path valid.
//check the document for any errors.
}
virtual int ExecuteCommand()
{
//copy the document
}
virtual int FinalizeCommand()
{
//delete temporaries if used.
}
};
class CPrintDocumentCommand : public ICommand
{
private:
std::string m_szDocumentName;
std::string m_szPageSettings;
int iTopMargin;
int iLeftMargin
public:
CPrintDocumentCommand(std::string _szDocumentName, std::_szPageSettings, int _iTopMargin, int iLeftMargin)
{
m_szDocumentName = _szDocumentName;
m_szPageSettings = _szPageSettings;
m_iTopMargin = _iTopMargin;
m_iLeftMargin = _iLeftMargin;
}
virtual int InitCommand()
{
//check the page settings.
//check the document for any errors.
//check printer
}
virtual int ExecuteCommand()
{
//print the document;
}
virtual int FinalizeCommand()
{
//delete temporary if used.
}
};
CCommandProcessor oProcessor;
CPrintDocumentCommand oPrintCommand("c:\\data\\report.txt", "some settings", 5, 5);
CCopyDocumentCommand oCopyCommand("c:\\data\\report.txt", "c:\\data\\report_.txt");
oProcessor.ProcessCommand(&oPrintCommand);
oProcessor.ProcessCommand(&oCopyCommand);
正如您所看到的那样CommandProcessor
执行不同的命令,这些命令可以处理不同的参数集。
也就是说,Command Pattern
允许您将parameters
的{{1}}转换为command function
的{{1}}。
答案 1 :(得分:1)
以下是更详细的structure diagram命令:
从这个结构中,你可以看到&#34;参数化对象&#34;应该是 Invoker 类中setCommand()方法的参数,参数的类型是命令界面。
所以&#34;用不同的请求参数化客户端&#34;应该意味着你可以传递不同的命令实例,然后你可以使用相同的executeCommand()方法调用来实现不同的操作。
答案 2 :(得分:0)
对我来说,参数化的真正含义并不清楚。我怀疑它只是意味着你可以为每个客户的接收者提供一堆不同的请求。
在适用性下,gof继续说:'当你想要使用命令模式
通过要执行的操作来参数化对象,如上面的MenuItem对象所做的那样。您可以使用回调函数在过程语言中表达此类参数化,也就是说,某个函数已注册到稍后要调用的某个位置。命令是面向对象的回调替换。 ...'