Double Dispatch 模式 (vistor模式是应用之一


本文介绍了常见面向对象语言(Java,C#,C++等)OverLoad对于运行时执行的方法邦定的局限,并且如何通过Double Dispatch来实现运行时行为邦定。

根据对象来选择行为问题

public interface Event {

}

public class BlueEvent implements Event {

}

public class RedEvent implements Event {

}

public class Handler {

public void handle(Event event){

System.out.println("It is event");

}

public void handle(RedEvent event){

System.out.println("It is RedEvent");

}

public void handle(BlueEvent event){

System.out.println("It is BlueEvent");

}

}

public class Main {

public static void main(String[] args) {

Event evt=new BlueEvent();

new Handler().handle(evt);

}

}

你认为运行结果是什么呢?

结果:It is event

是不是有点出乎意料,不是It is BlueEvent,这是应为Overload并不支持在运行时根据参数的运行时类型来帮定方法,所以要执行哪个方法是在编译时就选定了的。

2 Double Dispatch Pattern

由于Java,C++C#都具有上述局限,通常我们只能通过Switchif结构来实现,当然这种实现方式既不优雅而且影响代码的可维护性。

通过以下的Double Dispatch Pattern便可以优雅的实现。

public interface Event {

public void injectHandler(EventHandler v);

}

public class BlueEvent implements Event {

public void injectHandler(EventHandler v) {

v.handle(this);

}

}

public class RedEvent implements Event {

public void injectHandler(EventHandler v) {

v.handle(this);

}

}

public class EventHandler {

public void handle(BlueEvent e){

System.out.println("It is BlueEvent");

}

public void handle(RedEvent e){

System.out.println("It is RedEvent");

}

}

public class Main {

public static void main(String[] args) {

Event evt=new BlueEvent();

evt.injectHandler(new EventHandler());

}

}

其实设计模式(GoF)中的Visitor模式就是Double Dispatch的一种应用。

原文地址:https://www.cnblogs.com/kanego/p/kanego.html