例: 如仿QQ聊天室中,客户端发送不同命令,服务器端接收命令!我们经常会用switch或者if..else..等来处理,假如我们将客户端的命令看成对象即类来处理,这样扩展性更好!代码也比较好维护,代码复杂度会比较高.
简单的command模式实现
import java.util.HashMap;
abstract class Command{
public abstract void execute();
}
class LoadCommand extends Command{
public void execute(){
System.out.println("LoadCommand");
}
}
class newCommand extends Command{
public void execute(){
System.out.println("newCommand");
}
}
class SaveCommand extends Command
{
public void execute(){
System.out.println("saveCommand");
}
}
class RegiestCommand
{
HashMap hashmap = new HashMap();
public RegiestCommand()
{
hashmap.put("LoadCommand" , new LoadCommand());
hashmap.put("newCommand" , new newCommand());
hashmap.put("SaveCommand" , new SaveCommand());
}
public Command getObject(String key){
return (Command)hashmap.get(key);
}
}
public class TestCommand{
public static void main(String[] args){
String strCommand = args[0];
System.out.println("strCommand:" + strCommand);
RegiestCommand rc = new RegiestCommand();
Command cmd = (Command)rc.getObject(strCommand);
cmd.execute();
}
}
通过RegiestCommand注册所有命令,客户端发送命令,服务器端通过哈希表取得命令对象!
简单实现,RegiestCommand注册所有命令需要改进!!