Switch java的设计模式命令 [英] Design Pattern Command for Switch java

查看:149
本文介绍了Switch java的设计模式命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用此开关的设计模式 - 案例代码。
我试图使用命令模式,但我不明白如何(我只编程2个月)
我写了这个程序,以学习如何更好的程序。

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.

我的代码:

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

}

推荐答案

我从来没有想过改进创建shell的丑陋过程;从来没有使用过开关,但是很多 if-else ,这本质上是一样的。

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

这里有一个开始。 Command 实现不应该读取它们的输入(由于关注的分离),它们应该指定他们想要什么,并且某种读者应该提供它们(参见方法 Writer )。

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).

此外,我问自己如何设计 QuitProgram 命令 - 不使用 System.exit(0)

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

这篇关于Switch java的设计模式命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆