How to use Command pattern by passing to it runtime params
Asked Answered
C

1

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.

Caruthers answered 23/3, 2016 at 19:44 Comment(0)
P
4

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.

Pinard answered 23/3, 2016 at 21:2 Comment(5)
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.Caruthers
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 thatCaruthers
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 objectsCaruthers
I think you've fallen into an 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.Pinard
u right. please check my other question at: #36195378Caruthers

© 2022 - 2024 — McMap. All rights reserved.