Design Pattern Command for Switch java

喜你入骨 提交于 2020-01-03 06:36:11

问题


I want to use design pattern for this switch - case code. I tried to use the command pattern, but I could not understand how(I was programming only 2 for months) I wrote this program to learn how to better program.

My code:

public class Server {
private static final String READ_NEW_MESSAGES = "read new mes";
private static final String SEND_PRIVATE_MESSAGES = "send mes";
private static final String JOIN_CHAT = "find chat";
private static final String CREATE_CHAT = "chating";
private static final String QUIT = "quit";
private static final String EXIT = "exit";
private static final String REGISTRATION = "reg";
private static final String CREATE_PRIVATE_CHAT = "priv chat";
private static final String CONNECT_TO_PRIVATE_CHAT = "connect pm";
private static final String START_CHAT = "Start";
private Populator<PrivateMessage> privateMessagePopulator;
private Populator<Registration> registrationPopulator;
private Populator<Message> messagePopulator;
private Populator<PrivateChat> privateChatPopulator;
private Populator<Chat> publicChatPopulator;
private List<PrivateMessage> privateMessages;
private BufferedReader reader;
private String currentUser;
private Set<String> users;
private static Logger log = Logger.getLogger(Server.class.getName());
private List<Chat> chats;
private String password;
private Set<Registration> registration;
private List<PrivateChat> pmChat;
private String chatName;

public Server() {
    server();
}

public void server() {
    reader = new BufferedReader(new InputStreamReader(System.in));
    privateMessages = new ArrayList<PrivateMessage>();
    users = new HashSet<String>();
    chats = new ArrayList<Chat>();
    privateMessagePopulator = new PrivateMessagePopulator();
    privateChatPopulator = new PrivateChatPopulator();
    publicChatPopulator = new PublicChatPopulator();
    messagePopulator = new MessagePopulator();
    registrationPopulator = new RegistratorPopulator();
    registration = new HashSet<Registration>();
    pmChat = new ArrayList<PrivateChat>();
}

public void start() {
    String decition = "";

    while (true) {
        try {
            registrationOrLogin();
        } catch (IOException e1) {
            e1.printStackTrace();
        }

        while (decition != QUIT) {

            System.out.println("Create a chat - chating");
            System.out.println("Join the chat - find chat");
            System.out.println("Send private message - send mes");
            System.out.println("Read new messages - new mes");
            System.out.println("Quit - quit");
            System.out.println("Create private chat - priv chat");
            System.out.println("Connect to private chat - connect pm");

            try {
                decition = reader.readLine();
                switch (decition) {
                case CREATE_PRIVATE_CHAT:
                    createPrivateChat();
                    break;
                case CREATE_CHAT:
                    createChat();
                    break;
                case JOIN_CHAT:
                    joinChat();
                    break;
                case SEND_PRIVATE_MESSAGES:
                    sendPrivateMessage();
                    break;
                case READ_NEW_MESSAGES:
                    showNewMessages();
                    break;
                case QUIT:
                    logout();
                    break;
                case REGISTRATION:
                    registration();
                    break;
                case CONNECT_TO_PRIVATE_CHAT:
                    joinToPrivateChat();
                    break;

                default:
                    break;
                }
            } catch (IOException e) {
                log.warning("Error while reading decition from keyboard. "
                        + e.getMessage());
            }
        }
    }
}

private void sendPrivateMessage() throws IOException {
    PrivateMessage privateMessage = privateMessagePopulator.populate();
    privateMessage.setSenderName(currentUser);
    privateMessages.add(privateMessage);
}

private void joinChat() throws IOException {
    System.out.println("Exist public chat");
    for (Chat chat : chats) {
        System.out.println(chat.getChatName());
    }
    System.out.println("Enter the name of chat you wish to join");
    chatName = reader.readLine();
    for (Chat chat : chats) {
        if (chatName.equals(chat.getChatName())) {
            for (Message mes : chat.getMessages()) {
                System.out.println(mes.getSenderName() + ": "
                        + mes.getContent());
            }
            publicComunication(chat);
        }
    }
}

private boolean hasNewMessages() {
    boolean result = false;
    for (PrivateMessage privateMessage : privateMessages) {
        if (currentUser.equals(privateMessage.getReceiverName())) {
            result = true;
        }
    }

    for (PrivateChat pm : pmChat) {
        if (pm.getAddUserName().equals(currentUser)) {
            result = true;
        }
    }
    return result;
}

private void showNewMessages() {
    if (hasNewMessages()) {
        for (PrivateMessage privateMessage : privateMessages) {
            if (currentUser.equals(privateMessage.getReceiverName())
                    && MessageStatus.DIDNT_READ.equals(privateMessage
                            .getStatus())) {
                System.out.println(privateMessage.getSenderName() + ": "
                        + privateMessage.getContent());

            }
            privateMessage.setStatus(MessageStatus.ALREADY_READ);
        }
    }

    if (hasNewMessages()) {
        for (PrivateChat pm : pmChat) {
            for (Message message : pm.getMessages()) {
                if (pm.getAddUserName().equals(currentUser)) {
                    System.out.println(message.getSenderName() + ": "
                            + message.getContent());
                }
            }
        }
    } else {
        System.out.println("you don't have new message ");
    }
}

private void registrationOrLogin() throws IOException {
    String logOrReg;
    System.out
            .println("Hi,if you already have account - 1,\nIf you would like to register - 2");
    logOrReg = reader.readLine();
    if (logOrReg.equals("1")) {
        login();
    } else if (logOrReg.equals("2")) {
        registration();
    } else {
        registrationOrLogin();
    }
}

private boolean hasUser() {
    boolean result = false;
    for (Registration reg : registration) {
        if (currentUser.equals(reg.getUserName())
                && password.equals(reg.getUserPassword())) {
            result = true;
        }
    }
    return result;
}

private void login() throws IOException {
    System.out.println("Please,enter user name and password ");
    currentUser = reader.readLine();
    password = reader.readLine();
    if (hasUser()) {
        System.out.println("You already logged in system");
    } else {
        System.out.println("Wrong user name or password");
        registrationOrLogin();
    }
}

private void logout() throws IOException {
    currentUser = null;
    password = null;
    registrationOrLogin();

}

private void createChat() throws IOException {
    Chat chat = new Chat();
    chat = publicChatPopulator.populate();
    publicComunication(chat);
    chats.add(chat);
}

private void joinToPrivateChat() throws IOException {
    for (PrivateChat pm : pmChat) {
        for (String user : pm.getUsers()) {
            if (user.equals(currentUser)) {
                System.out.println(pm.getChatName());
            }
        }
    }
    System.out.println("Enter the name of the chat you wish to join");
    chatName = reader.readLine();
    for (PrivateChat pm : pmChat) {

        if (chatName.equals(pm.getChatName())) {

            for (Message message : pm.getMessages()) {
                System.out.println(message.getSenderName() + " "
                        + message.getContent());
            }
            privateComunication(pm);
        }

    }

}

private void createPrivateChat() throws IOException {
    PrivateChat privateChat = new PrivateChat();
    Set<String> chatUsers = new HashSet<String>();
    privateChat = privateChatPopulator.populate();
    while (true) {
        privateChat.setAddUserName(reader.readLine());
        chatUsers.add(privateChat.getAddUserName());
        privateChat.setUsers(chatUsers);
        for (String user : users) {
            if (user.equals(privateChat.getAddUserName())) {
                System.out.println("you add too chat user - "
                        + privateChat.getAddUserName());
            }
        }
        if (privateChat.getAddUserName().equals(START_CHAT)) {
            break;
        }

    }
    privateComunication(privateChat);
    pmChat.add(privateChat);
}

private void registration() throws IOException {
    Registration reg = registrationPopulator.populate();
    registration.add(reg);
    currentUser = reg.getUserName();
    users.add(reg.getUserName());

}

private void privateComunication(PrivateChat privateChat) {
    while (true) {
        Message message = messagePopulator.populate();
        message.setSenderName(currentUser);
        System.out.println(message.getSenderName());
        System.out.println("\t" + message.getContent());

        if (EXIT.equals(message.getContent())) {
            break;
        }
        privateChat.setStatus(MessageStatus.DIDNT_READ);
        privateChat.addMessage(message);
    }
}

private void publicComunication(Chat chat) {
    while (true) {
        Message message = messagePopulator.populate();
        message.setSenderName(currentUser);
        System.out.println(message.getSenderName());
        System.out.println("\t" + message.getContent());

        if (EXIT.equals(message.getContent())) {
            break;
        }
        chat.addMessage(message);
    }
}

}


回答1:


I never thought about improving the ugly process of creating shells; never used a switch, but a lot of if-elses, which is the same essentially.

package command.example;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class CommandExample implements ApplicationContext {
    private final Writer writer = new BufferedWriter(new OutputStreamWriter(
            System.out));
    private boolean quit = false;

    private Map<String, Command> commands = new HashMap<>();
    {
        commands.put("create", new CreateChat(this));
        commands.put("join", new JoinChat(this));
        commands.put("exit", new ExitCommand(this));
    }

    public static void main(String[] args) throws Exception {
        CommandExample example = new CommandExample();
        example.run();
    }

    public void run() throws IOException {
        try (Scanner s = new Scanner(System.in)) {
            writer.write("> ");
            writer.flush();
            while (!quit && s.hasNextLine()) {
                String input = s.nextLine().trim();

                // get or default is java8, alternatively you could check for null
                Command command = commands.getOrDefault(input, new UnknownCommand(this, input));
                command.execute();

                if (!quit)
                    writer.write("> ");
                writer.flush();
            }
        }
    }

    @Override
    public void shutdown() {
        quit = true;
    }

    @Override
    public Writer getWriter() {
        return writer;
    }

    static interface Command {
        public void execute() throws IOException;
    }

    static abstract class AbstractCommand implements Command {
        protected final ApplicationContext context;
        protected final Writer writer;

        public AbstractCommand(ApplicationContext context) {
            this.context = context;
            this.writer = context.getWriter();
        }
    }

    static class CreateChat extends AbstractCommand {
        public CreateChat(ApplicationContext context) {
            super(context);
        }

        @Override
        public void execute() throws IOException {
            writer.write(String.format("Successfully created a chat!%n"));
            writer.flush();
        }
    }

    static class JoinChat extends AbstractCommand {
        public JoinChat(ApplicationContext context) {
            super(context);
        }

        @Override
        public void execute() throws IOException {
            writer.write(String.format("Successfully joined chat!%n"));
            writer.flush();
        }
    }

    static class UnknownCommand extends AbstractCommand {
        private final String command;

        public UnknownCommand(ApplicationContext context, String command) {
            super(context);
            this.command = command;
        }

        @Override
        public void execute() throws IOException {
            writer.write(String.format("'%s' is not a supported command!%n",
                    command));
            writer.flush();
        }
    }

    static class ExitCommand extends AbstractCommand {
        public ExitCommand(ApplicationContext context) {
            super(context);
        }

        @Override
        public void execute() throws IOException {
            writer.write(String.format("Application is shutting down!%n"));
            writer.flush();
            context.shutdown();
        }
    }
};

interface ApplicationContext {
    public void shutdown();
    public Writer getWriter();
}

Here you have a little start. The Command implementations should not read their input (due to separation of concern), they should specify what they want and some kind of reader should provide it to them (cf. the approach with Writer).

Furthermore I'm asking myself how one would design the QuitProgram command - without using System.exit(0).



来源:https://stackoverflow.com/questions/29399298/design-pattern-command-for-switch-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!