rayman rayman - 5 months ago 35
Java Question

How to use Command pattern by passing to it runtime params

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 {

public void execute(String msg){

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

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



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.