我正在编写一个简单的分布式java rmi应用程序,我有一堆方法,每个方法都需要遍历客户端接口的映射,以便在这些接口上调用各种其他方法,如下所示:
public void methodX (arg1, arg2) { Iteratoritr = clients.keySet().iterator; while (itr.hasNext()) { String name = itr.next(); if (!"mod".equals(name)) { try { clients.get(name).methodXX(arg1, arg2); } catch(RemoteException ex) { // do something } } } } public void methodY (arg1, arg2, arg3) { Iterator itr = clients.keySet().iterator; while (itr.hasNext()) { String name = itr.next(); if (!"mod".equals(name)) { try { clients.get(name).methodYY(arg1, arg2, arg3); } catch(RemoteException ex) { // do something } } } }
现在我修改了这些,以便它们通过传递一个名为MESSAGE_TYPE的新参数来调用单个方法doAll,如下所示:
public void methodX (arg1, arg2) { doAll(MESSAGE_TYPE.METHODX, arg1, arg2, null); } public void methodY (arg1, arg2, arg3) { doAll(MESSAGE_TYPE_METHODY, arg1, arg2, arg3); }
和doAll方法:
public void doAll(msg_type, arg1, arg2, arg3) { Iteratoritr = clients.keySet().iterator; while (itr.hasNext()) { String name = itr.next(); if (!"mod".equals(name)) { try { switch(msg_type) { case METHODX: clients.get(name).methodXX(arg1, arg2); break; case METHODY: clients.get(name).methodYY(arg1, arg2, arg3); break; } } catch(RemoteException ex) { // do something } } } }
现在有更多这样的方法,所以我的doAll方法需要一堆args,每个调用它的methodXX都会传递一堆空值.
我可以重写这个,这样更简洁吗?如果是这样,你能提供一个例子吗?
首先,我将使用增强的for循环,并按照条目中的建议迭代条目而不是键:
public void doAll(arg1, arg2, arg3) { for (Map.Entryentry : clients.entrySet()) { if (!"mod".equals(entry.getKey())) { try { switch(MESSAGE_TYPE) { case METHODX: entry.getValue().methodXX(arg1, arg2); break; case METHODY: entry.getValue().methodYY(arg1, arg2, arg3); break; } } catch(RemoteException ex) { // do something } } } }
我想我会重构它以传递一个"动作"来调用每个客户端,并使用来自调用站点的匿名内部类:
public interface RemoteAction { public void execute(Client client) throws RemoteException; } public void doAll(RemoteAction action) { for (Map.Entryentry : clients.entrySet()) { if (!"mod".equals(entry.getKey())) { try { action.execute(entry.getValue()); } catch(RemoteException ex) { // do something } } } } public void methodX (final arg1, final arg2) { doAll(new Action() { @Override public void execute(Client client) throws RemoteException { client.methodX(arg1, arg2); } }); } public void methodY (final arg1, final arg2, final arg3) { doAll(new Action() { @Override public void execute(Client client) throws RemoteException { client.methodY(arg1, arg2, arg3); } }); }
它不像支持lambda表达式的语言那样好,但它比switch语句更好.