我应该使用模式吗

所以我从 twitch irc 收到一个字符串,并根据该命令执行一些代码。问题是我可以简化我的代码或使用模式。问题是大多数命令具有相同的代码,只有回复发生了变化。你可以看到下面的代码。它看起来很乱,添加新命令或功能可能会很痛苦(如果我有 200 个或更多命令),而且大部分代码都是相同的。


public void onCommand(User user, Channel channel, String command)

    {


        // some if statements 


        switch (command.toLowerCase()){

        case "hi":{


            //some simple action

        }

        case "fire":{


            vote(60, channel, "fire")

        }

        ...


        //timeout

    }


    void vote(int duration, final Channel channel, String voteFor){

        Timer timer = new Timer();


        timer.schedule(new TimerTask() {

            @Override

            public void run() {

                //start voting

            }, duration);


            switch (voteFor){

                case "fire":{

                    if (voteYes > voteNo) {

                        //some action

                    }else

                        //some action

                    break;

                }

                ...

    }  

PS 我尝试使用策略模式,但感觉没有必要。


人到中年有点甜
浏览 122回答 2
2回答

摇曳的蔷薇

使用地图:class CommandProcessor {&nbsp; interface Command {&nbsp; &nbsp; String executeForKey();&nbsp; &nbsp; void execute(User user, Channel channel);&nbsp; }&nbsp; class OnFireCommand implements Command {&nbsp; &nbsp; public String executeForKey() { return "fire"; }&nbsp; &nbsp; public void execute() {}&nbsp; }&nbsp; Map<String, Command> map = new HashMap<>();&nbsp; CommandProcessor() {&nbsp; &nbsp; // this will become a simple listing of commands&nbsp; &nbsp; put(new OnFireCommand())&nbsp; }&nbsp; void put(Command c) {&nbsp; &nbsp; map.put(c.executeForKey(), c);&nbsp; }&nbsp; public void onCommand(User user, Channel channel, String command) {&nbsp; &nbsp; this.map.get(command).execute(user, channel);&nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java