mercredi 22 janvier 2020

how to avoid switch statement?

I'm trying to learn client/server in java until now i got the basics. here how to accept and serve out many clients

public class Server {
    ServerSocket serverSocket;

    public void startServer() throws IOException {
        serverSocket= new ServerSocket(2000);
        while (true){
            Socket s= serverSocket.accept();
            new ClientRequestUploadFile(s).start(); //here is the first option.
        }
    }
}

Now suppose i have too many type of options the client can request. the code will be as follow :

public void startServer() throws IOException {
        serverSocket= new ServerSocket(2000);
        while (true){
            Socket s= serverSocket.accept();
            DataInputStream clientStream= new DataInputStream(s.getInputStream());
            String requestName=clientStream.readUTF();
            switch (requestName){
                case "ClientRequestUploadFile": new ClientRequestUploadFileHandler(s).start();break;
                case "clientRequestCalculator": new clientRequestCalculatorHandler(s).start();break;
                case "clientRequestDownloadFile": new clientRequestDownloadFileHandler(s).start();break;
            }
        }
    }

if there 100 of options,is there any way to avoid switch statement(design-patterns maybe)? keep in mind that may occur new option in the future.

Aucun commentaire:

Enregistrer un commentaire