要求:用java中的socket API实现一个TCP服务器,服务器可以同时处理多个客户端。服务器可以在 XML 文本文件中添加/删除 ... 项目(作为数据存储) 客户端可以向服务器发送命令,例如“addItem”/“removeItem” .. 如果客户端发送了“addItem”,则应将新节点添加到 XML 文档中。
应该使用命令设计模式吗?如果是这样,哪个应该是命令,接收者,调用者,客户端?
我的实现如下(评论中还有一些问题):
interface Command{
public void execute();
}
AddItemCommand implements Command{
//The receiver
XMLFileHelper xmlHelper;
//The data need to added to XML file
//This data should be here or not??
ItemNode addedNode;
public AddItemCommand(XMLFileHelper newHelper){
xmlHelper = newHelper;
}
public void execute(){
xmlHelper.addItemNode(addedNode);
}
}
/*this class will handle all the xml doc operation: add, remove ...
i guess, it is should be the receiver
DataHelper in the parent interface, subclass could be XMLFileHelper, DBHelper, MessageQueueHelper ...
*/
public class XMLFileHelper implements DataHelper{
}
RemoveItemCommand implements Command(){
//...............
}
/*This is the invoker, i am not sure what should it be, so i do not have a good name for it.*/
public class Invoker{
Map<String, Command> map = new HashMap<String, Command>();
public void addCommand(String cmdName, Command c){
map.put(cmdName, c);
}
public void processRequest(String reqName){
map.get(reqName).execute();
}
}
TcpServerThread implements Runable{
public void run(){
DataHelper xmlPaser = new XMLFileHelper();
Command cmd1 = new AddItemCommand();
Command cmd2 = new RemoveItemCommand();
Invoker invoker = new Involer();
invoker.addCmd("add", cmd1);
invoker.addCmd("remove", cmd2);
String cmdName = getCommandName(socket.getInputStream());
invoker.processRequest(cmdName);
}
}