I'm writing a client-server app and I'm having a problem with using command pattern. In my program server recieves a String input command from a client, finds proper command for the input in the HashMap, executes it and sends back the return value. I'm having a problem with figuring out, how to write the commands that require more than 1 step(command has to ask ask a client for extra paramether/s and then should return final result).
command interface
public interface Command {
public String execute();
}
server communication with a client
try {
ServerSocket serverSocket = new ServerSocket(port);
Command c;
while(true) {
Socket clientSocket = serverSocket.accept();
PrintWriter clientSocketWriter = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader clientSocketReader = new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));
String inputLine;
//server recieves String command from client and sends back the result while semaphore is true
while (Main.semaphore) {
inputLine = clientSocketReader.readLine();
c = CommandFactory.getCommandByName(inputLine);
clientSocketWriter.println(c.execute());
}
serverSocket.close();
clientSocketWriter.close();
clientSocketReader.close();
clientSocket.close();
}
} catch(Exception e) {
e.printStackTrace();
}
in one step commands there in no problem
public class CommandHelp implements Command {
@Override
public String execute() {
//returns string of all commands
return CommandFactory.getCommandByNames();
}
I don't know how to write a command, that needs an extra paramether for executing, it can't return the result right away without knowing it. Command should return number of permutations from x elements(client should choose).
public class CommandPermutationsCount implements Command {
@Override
public String execute() {
//can't return anything yet
}
public long getPermutations(int elementsCount) {
long result = 1;
for (int factor = 2; factor <= elementsCount; factor++) {
result *= factor;
}
return result;
}
}
I've had an idea to make the Command void instead of String, but then I wouldn't be able to send comunicate with a client via clientSocketWriter. Is there any good way to make commands with more steps?