How to use Command pattern by passing to it runtime params

♀尐吖头ヾ 提交于 2019-12-02 12:28:04

问题


I have functionality that I am encapsulate on diff commands using Command pattern.

I am creating the command with the information and logic it need how ever I am getting some params only on runtime which I need to provide my commands

for example:

public class sendMessageToServerCommand implements Command {

    @Override
    public void execute(String msg){
          sendToServerTheMsg(msg);
    }
}

..
Command command=new sendMessageToServerCommand();
command.execute("msg I got on runtime");

Perhaps I shouldnt use command pattern and think about something else? suggestions ?

Thanks.


回答1:


The Command pattern stipulates an object that can be executed with no arguments after its creation (for example: Runnable or Callable) however, there is nothing preventing arguments from being passed during creation; so you can simply move the msg argument from the execute() method to the command's constructor.

In a typical use of the Command pattern, commands are created in one place and executed in another. The creation logic is parameterized; the execution logic is not.



来源:https://stackoverflow.com/questions/36187330/how-to-use-command-pattern-by-passing-to-it-runtime-params

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!