开发者

command pattern for this scenario? advice

开发者 https://www.devze.com 2023-02-11 10:45 出处:网络
good evening all. ive been reading up on the command pattern and im wondering if it\'s a good fit for what i want to build.

good evening all. ive been reading up on the command pattern and im wondering if it's a good fit for what i want to build.

essentially, i have a client that forms a socket connection with a server. there is 1 class 'foo' on my server that the client needs to invoke methods against.

lets say foo has 5 methods that my client will invoke. i have made the mistake in the past of marshalling an object that is demarshalled on the server. then i check a variable in the object and using a switch statement, the server logic can determine what action should be invoked.

i want to avoid this and so i believe the command pattern may help me. but, for my example 'foo' class on the server, do i need to create a command class for each method that is to be invoked in foo? shoul开发者_如何学JAVAd the class that is sent from the client to the server be a command class? will i only need 1 receiver in this case? - the foo class?

thanks very much for your help and sorry about the 'foo' class name here. i havent got any concrete class names yet!

best regards


No matter what you do, you will not be able to entirely get rid of that switch() statement. Command pattern would suggest you do the following:

abstract class AbstractCommand() {
  abstract void execute();
}
class ConcreteCommand extends AbstractCommand {
  // execute implementation
}
// more command classes as needed; probably one per each of your method calls

Then you have a command factory:

class CommandFactory {
  AbstractCommand createCommandForMessage(Message m) {
    // ... switch() goes here
  }
}

And your message receiving part becomes as simple as this:

public class MessageReceiver {
  public void work() {
    while (true) {
      Message m = receiveMessage();
      AbstractCommand command = commandFactory.createCommandForMessage(m);
      command.execute();
    }
  }
}

What's nice about this is that you cleanly separate the actual logic of commands (execute() method implementations) from the logic that decides which command to use, from the logic that knows how to receive messages on the network.

0

精彩评论

暂无评论...
验证码 换一张
取 消