java单双派机制理解
引言:Java是一个支持双分派的单分派语言
知道java是支持后期动态绑定,也知道访问者模式,但是两者之间的关系,还真不知道,况且在这之间还有一个静态绑定。
1.动态绑定
class Father { public void method(){ System.out.println("This is Father's method"); } } class Son1 extends Father{ public void method(){ System.out.println("This is Son1's method"); } } class Son2 extends Father{ public void method(){ System.out.println("This is Son2's method"); } } public class Test { public static void main(String[] args){ Father s1 = new Son1(); s1.method(); Father s2 = new Son2(); s2.method(); } }
打印结果:
This is Son1′s method
This is Son2′s method
使用过java的,这上面的结果,都会不屑一顾。那么在看下面一个例子,反正我自己是傻眼了
2.静态绑定
class Father { } class Son1 extends Father { } class Son2 extends Father { } class Execute { public void method(Father father) { System.out.println("This is Father's method"); } public void method(Son1 son) { System.out.println("This is Son1's method"); } public void method(Son2 son) { System.out.println("This is Son2's method"); } }
很神奇的发现,打印了结果是这样
This is Father's method
This is Father's method
This is Father's method
对于重载,只是在编译的时候,就已经决定了。是根据申明对象来选择具体调用哪个重载的方法,因此才会全部调用父类的方法
当然,我们可以通过instanceof关键字来处理,但是这样,如果有较多子类,这样逻辑判断起来就会很别扭,而且没增加一个子类,都需要新增一个if else 否则,代码就会出现问题
这样,就明白了,引言说的,java是单派语言。那么如何理解,支持双派呢?答案在于java可以通过访问者模式来实现双派机制
首先,看下一个简单的例子
class Visitor_A { public void method1() { System.out.println("Visitor_A dosomething"); } public void method2(Visitor_B b) { b.callA(this); } } class Visitor_B { public void callA(Visitor_A a) { a.method1(); } } public static void main(String[] args) { Visitor_A visitor_a = new Visitor_A(); Visitor_B visitor_B = new Visitor_B(); visitor_a.method1(); visitor_B.callA(visitor_a); }
上面,就是访问者模式的最基础形式,通过观察者B来访问A的接口,来实现双派能力,其实也是使用本质也是依赖了java的后期动态绑定机制能力
class Father { public void accept(Execute exe){ exe.method(this); } } class Son1 extends Father{ public void accept(Execute exe){ exe.method(this); } } class Son2 extends Father{ public void accept(Execute exe){ exe.method(this); } } class Execute { public void method(Father father){ System.out.println("This is Father's method"); } public void method(Son1 son){ System.out.println("This is Son1's method"); } public void method(Son2 son){ System.out.println("This is Son2's method"); } } public class Test { public static void main(String[] args){ Father father = new Father(); Father s1 = new Son1(); Father s2 = new Son2(); Execute exe = new Execute(); father.accept(exe); s1.accept(exe); s2.accept(exe); } }
想了解更多理论讨论,可以移步这里:http://www.iteye.com/topic/1130764