Reputation: 97
For example suppose I have two different computers running a node represented by the class Node. Each node is listening on a ServerSocket. I am trying to apply the command pattern. I have a interface Command
public interface Command{
public void execute();
}
Now I want to create a class that implements Command so that when it is executed it will print on the screen the id of the Node it was sent to. How can I accomplish this if I have no way of getting a reference to the Node object whose ID I want to print, since it is executing on a remote computer?
public class PrintCommand implements Command{
public void execute(){
System.out.println("This node's id is " + ??);
}
Is the command pattern only really possible to apply for execution in the same machine?
Upvotes: 0
Views: 541
Reputation: 515
You can use the command-pattern for network-excercices. As you wrote, you can't get a reference of a Node-Object on a remote machine. That is wrong. With techniques like Java RMI it is possible to work with references on remote objects that are located in another JVM. If you did not work with network issues until know, it may be a bit hard to understand at first, but in fact it is very easy to use.
If you want to work more rudimentary, you could send a String or maybe just a number from machine A to machine B over your sockets that will call the execute-Method from the Command-Interface. As machine B knows its own Node-Object, you can print it out there very easy. If you want to print out the id of Node A on machine B, you have to send its id to B.
An approach for this could be to use serialization. You can serialize an object for example to json and send it over your network-connection. On the other machine, you deserialize it to an object and pass it to your execute()-method.
Upvotes: 1