适配器设计模式和匿名内部类的应用

来源:互联网 发布:数据库 restoring 编辑:程序博客网 时间:2024/05/21 13:58
       今天遇到这么一个问题,实现在后台执行某个方法时,前台显示busy信息并锁屏,等后台方法执行后,再解锁。。在ZK框架中,单纯实现这样的功能不难,但要实现可重用性,可供任意方法嵌套是难点。。

zk 显示busy信息的可以用以下方法    

        Clients.showBusy("Processing...");
        Events.echoEvent("onShowBusy", this, handler);
    public void onShowBusy(final Event evt) {
       //do some thing
        Clients.clearBusy();

    }

        要在//do some thing 位置嵌入自己要执行的方法,而且这些方法可能来源于很多不同的类和很多不同的操作,search,load,upload等十几个地方,当然,可以在有需要的方法的类中加入这几行代码,但这样就大大降低了代码的可重用性,也不便于统一管理。。

       起初想法是将类,类中的方法,方法用到的参数,统统传过来,在do something位置执行:
    public void showBusy(final String mes, final Component component, final Method method,            final Object[] parameters) {        // Object obj = Class.forName(className).getInterfaces();        final Map dataMap = new HashMap();        dataMap.put("method", method);        dataMap.put("parameters", parameters);        dataMap.put("target", component);        Clients.showBusy(mes);        Events.echoEvent("onShowBusy", this, dataMap);    }    public void onShowBusy(final Event evt) {        final Map dataMap = (HashMap) evt.getData();        final Method met = (Method) dataMap.get("method");        final Object[] parameters = (Object[]) dataMap.get("parameters");        final Object obj = dataMap.get("target");        try {            met.invoke(obj, parameters);        } catch (final UiException e) {            e.printStackTrace();        } catch (final IllegalAccessException e) {            e.printStackTrace();        } catch (final InvocationTargetException e) {            e.printStackTrace();        }        Clients.clearBusy();    }
  

写出来后被自己拙劣的想法和糟糕的代码恶心到了,check in上去肯定被骂个半死,于是找个前辈问了下解决方法,得到的答案是,接口和匿名内部类。。

public interface BusyMessageHandler {    public void beforeBusy();    public void inBusy();    public void afterBusy();}public class DefaultBusyMessageHandler implements BusyMessageHandler{    @Override    public void afterBusy() {    }    @Override    public void beforeBusy() {    }    @Override    public void inBusy() {    }}
使用的方法修改成:

    public void showBusy(final BusyMessageHandler handler) {        handler.beforeBusy();        Clients.showBusy("Processing...");        Events.echoEvent("onShowBusy", this, handler);    }    public void onShowBusy(final Event evt) {        final BusyMessageHandler handler = (BusyMessageHandler) evt.getData();        handler.inBusy();        Clients.clearBusy();        handler.afterBusy();    }

这样一来,在需要show busy的地方将要执行的操作放在一个匿名内部类作为参数传过来就可以了。

showBusy(new DefaultBusyMessageHandler() {
                @Override
                public void inBusy() {
                    //do something you want
                }
            });

       用接口作为方法行参,用匿名内部类作为实参,确实是个很不错的想法,抽象类空实现接口的做法也符合适配器设计模式,不仅可以做要执行的方法,还能根据具体情况复写beforeBusy和afterBusy,使整个设计更灵活。。。