interface Chongqiwawa{ public void makeLove(String name); }
class Person{ Chongqiwawa wawa; public void setWawa(Chongqiwawa wawa){ this.wawa = wawa; } private String name; public void makeLove(){ //调用wawa的makeLove方法 wawa.makeLove(name); } 现在,你想和wawa那个,就可以这样用了: main(){ Person you = new Person(); you.makeLove(); }
class USAWawa implements Chongqiwawa{ public void makeLove(String name){ System.output.println(name + " come on! a,a, a..."); } } 好吧,你已经流口水了,一口价成交,然后带回家,迫不及待实践一下,代码体现为: main(){ Person you = new Person(); Chongqiwawa wawa = new USAWawa(); you.setWawa(wawa); you.makeLove(); }
这时候你已经可以和娃娃水乳交融了。不久,你发觉厌倦了美国娃娃,想试下日本娃娃,再次来到成人超市,日本娃娃makeLove功能实现如下: class JapanWawa implements Chongqiwawa{ public void makeLove(String name){ System.output.println(name + " yemede! a,a, a...ganbade..."); } } OK,你直接丢下一堆钞票一句不用找就抱回家了,马上进入主题:
main(){ Person you = new Person(); //获得实际的wawa Chongqiwawa wawa = new JapanWawa(); you.setWawa(wawa); you.makeLove(); } 看见了吗,只需改动一行代码,你就实现了娃娃的切换,得到不同的makeLove感受,其他代码都不用改。