本文共 915 字,大约阅读时间需要 3 分钟。
先设想一个场景,为系统设计一个命令行界面,用户输入命令来执行某项功能。系统的功能会不断添加,命令也会不断增加,如何将一项一项的功能加入到这个命令行界面?你可能会写出下面一段代码:
public class Receiver{ public void receive(String command) { switch (command) { case "command-1": …… break; case "command-2": …… break; case "command-3": …… break; …… } System.out.println("不支持此命令" + command); }}
按照这种写法,如果新增或修改对应的命令,则需要改动到这里的代码,耦合度比较好,不够灵活。
这时候就需要用到命令模式,以命令的方式,解耦调用者与功能具体实现者,降低系统耦合度,提供了灵活性
Servlet、Controller、线程池
public class Receiver{ //命令和对应的处理类集合 private Mapcommands; //注册命令和对应的处理类 public void register(String strComm,Command command){ commands.put(strComm,command); } public void receive(String command) { Command commandObj = commands.get(command); if(commandObj != null){ commandObj.execute(); return; } System.out.println("不支持此命令" + command); }}
转载地址:http://owpxi.baihongyu.com/