1

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.

jaco0646
  • 15,303
  • 7
  • 59
  • 83
rayman
  • 20,786
  • 45
  • 148
  • 246

1 Answers1

3

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.

jaco0646
  • 15,303
  • 7
  • 59
  • 83
  • I am using Spring for this. and I am creating those command entities in advanced. I cant provide those runtimes params in advanced only on execution time. – rayman Mar 23 '16 at 21:04
  • The thing is that I have a map of key object store that by action-key I know which command to execute. i am getting the action key on the invoker class. still try to understand my way how to glue all of that – rayman Mar 23 '16 at 21:13
  • I mean i am creating those objects on other place when initiliaizing my app. than based on action I know which one to use. and on usage-time(runtime) i need to pass it params that will be executed on the command objects – rayman Mar 23 '16 at 21:19
  • I think you've fallen into an [XY problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). My recommendation is to spend some time thinking about what you're really trying to solve and then either update this question or ask a new one. – jaco0646 Mar 23 '16 at 21:34
  • u right. please check my other question at: http://stackoverflow.com/questions/36194878/how-to-avoid-ifs-and-provide-runtime-params-on-execution – rayman Mar 24 '16 at 07:11