2017-12-26 2 views
0

클라이언트 - 서버 앱을 쓰고 있는데 명령 패턴을 사용하는 데 문제가 있습니다. 내 프로그램 서버에서 클라이언트로부터 문자열 입력 명령을 받고, HashMap에서 입력에 대한 적절한 명령을 찾아서 실행하고 반환 값을 되돌려 보냅니다. 알아내는 방법에 문제가 있습니다. 하나 이상의 단계가 필요한 명령을 작성하는 방법 (명령은 클라이언트에게 추가 매개 변수/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; 
    } 

}

내가 대신 문자열의 명령 무효을 할 생각을 했어,하지만 나는 clientSocketWriter를 통해 클라이언트와 comunicate 수를 송신 할 수 없습니다. 더 많은 단계로 명령을 내리는 좋은 방법이 있습니까?

+0

실행의 논리를 캡슐화하는 것이 전부입니다. 당신이하려는 것은 로직을 서버에 노출시키는 것입니다. – tsolakp

답변

0

나는 당신이 올바른 길에 있다고 생각합니다. 명령 식별자와 인수를 한 줄에 전달할 수있는 이유는 무엇입니까? 내가 좋아하는 뭔가 생각하고 있어요 : 당신이 보이는 추상 Command 클래스에서 상속 특정 명령 구현을 만들 수 있습니다 지금

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); 
    } 
} 

: 인수로 지정된 명령을 허용함으로써

>> permute -a 12 
>> shuffle -a [1, 2, 7, 6, 5, 3, 1] 
>> add -a 4 -a 5 

, 당신의 CommandFactory 뭔가처럼된다 이런 식으로 :

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(); 
} 
관련 문제