package com.iteye.badpie.javacode.duotai; /** * 人民警察 */ public interface IPolice { /** * 抓小偷 */ public void catchThief(); }
package com.iteye.badpie.javacode.duotai; /** * 一个警察,执行抓小偷任务. */ public class PoliceReal implements IPolice { @Override public void catchThief() { System.out.println("抓住小偷了"); } }
package com.iteye.badpie.javacode.duotai; /** * 另一个警察,也执行抓小偷任务. */ public class PoliceHyp implements IPolice { @Override public void catchThief() { System.out.println("大冷天的抓什么小偷啊,不如偷个菜."); } }
package com.iteye.badpie.javacode.duotai; /** * 市民 */ public class Citizen { private String mName; public Citizen(String name) { mName = name; } /** * 市民报案 */ public void report(IPolice police) { System.out.println(String.format("市民%s丢失手机,向警察报案抓小偷.", mName)); police.catchThief(); } }
市民虽然向警察报了案, 但你不知道能不能把小偷抓住, 甚至你都不知道他们有没有去抓小偷, 还有可能你在电影里看到的剧情真的发生了...
事情经过可能是这样:
package com.iteye.badpie.javacode.duotai; public class Main { public static void main(String[] args) { Citizen citizen = new Citizen("张三"); IPolice police = getPolice(); citizen.report(police); } private static IPolice getPolice() { return new PoliceReal(); } }
事情结果一:
市民张三丢失手机,向警察报案抓小偷. 抓住小偷了
事情经过也可能是这样:
package com.iteye.badpie.javacode.duotai; public class Main { public static void main(String[] args) { Citizen citizen = new Citizen("张三"); IPolice police = getPolice(); citizen.report(police); } private static IPolice getPolice() { return new PoliceHyp(); } }
事情结果二:
市民张三丢失手机,向警察报案抓小偷. 大冷天的抓什么小偷啊,不如偷个菜.
事情经过还可能是这样:
package com.iteye.badpie.javacode.duotai; public class Main { public static void main(String[] args) { Citizen citizen = new Citizen("张三"); IPolice police = getPolice(); citizen.report(police); } private static IPolice getPolice() { return new PoliceReal() { @Override public void catchThief() { System.out.println("抓小偷?笑话,抓了小偷我哪儿收保护费去啊."); } }; } }
事情结果三:
市民张三丢失手机,向警察报案抓小偷. 抓小偷?笑话,抓了小偷我哪儿收保护费去啊.