我正在编写一个客户端 - 服务器应用程序,我遇到了使用命令模式的问题。在我的程序服务器中从客户端收到一个String输入命令,在HashMap中找到输入的正确命令,执行它并发回返回值。我遇到问题,如何编写需要超过1步的命令(命令必须要求客户询问额外的参数/ s然后应返回最终结果)。
命令界面
public interface Command {
public String execute();
}
服务器与客户端的通信
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();
}
一步命令没有问题
public class CommandHelp implements Command {
@Override
public String execute() {
//returns string of all commands
return CommandFactory.getCommandByNames();
}
我不知道如何编写命令,需要额外的参数才能执行,它不能在不知情的情况下立即返回结果。命令应该返回x个元素的排列数(客户端应该选择)。
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;
}
}
我有一个想法让Command无效而不是String,但是后来我无法通过clientSocketWriter与客户端发送通信。有没有什么好方法可以用更多步骤制作命令?
答案 0 :(得分:0)
我认为你正走在正确的轨道上。为什么不允许命令标识符及其参数在一行中传递?我想的是:
>> permute -a 12
>> shuffle -a [1, 2, 7, 6, 5, 3, 1]
>> add -a 4 -a 5
通过允许使用参数指定的命令,CommandFactory
变为类似:
class CommandFactory {
public static Command parseCommand(String commandLine) {
// Tokenize commandLine:
// - First word is commandId
// - Tokens following '-a' string are arguments
// Return CommandHelp if no command with provided commandId is found
return CommandHelp(commandLine);
}
}
现在,您可以创建继承自如下所示的抽象Command
类的特定命令实现:
abstract class Command {
private final String commandId;
private final String commandArguments;
Command(String commandId, List<String> commandArguments) {
this.commandId = commandId;
this.commandArguments = commandArguments;
}
abstract String execute();
}