package com.designpatterns.adapter;/*** 定义鸭子接口*/
public interface Duck {/*** 定义鸭子呱呱叫(quack)*/public void quack();public void fly();
}package com.designpatterns.adapter;/*** 实现一个绿头鸭*/
public class MallarDuck implements Duck{@Overridepublic void quack() {System.out.println("MallarDuck(绿头鸭)");}@Overridepublic void fly() {System.out.println("I'm flying!");}
}package com.designpatterns.adapter;/*** 定义火鸡接口*/
public interface Turkey {/*** 定义咯咯叫(gobble)*/public void gobble();public void fly();
}package com.designpatterns.adapter;/*** 实现一个野火鸡*/
public class WildTurkey implements Turkey{@Overridepublic void gobble() {System.out.println("咯咯叫");}@Overridepublic void fly() {System.out.println("i'm flying a short distance");}
}package com.designpatterns.adapter;/** ** 定义一个适配器:adapter** 鸭子对象短缺,用一些火鸡对象来充数;不能堂而皇之的用火鸡,因为他们接口不同** 现实生活例子:*中国充电器插口与美国充电器插口,一个是扁的,一个是园的,出差去美国,必须买一个转接头(适配器), *在美国给自己电脑充电,必须先给自己的插口装上转接头,方可使用美国的充电口** 滥竽充数寓言故事*/
public class TurkeyAdapter implements Duck{Turkey turkey;public TurkeyAdapter(Turkey turkey){this.turkey=turkey;}@Overridepublic void quack() {turkey.gobble();}@Overridepublic void fly() {//火鸡的飞行距离短,火鸡就飞5倍距离,弥补与鸭子的飞行距离差距for(int i=0;i<5;i++){turkey.fly();}}
}package com.designpatterns.adapter;/*** 测试适配器*/
public class DuckTestDive {public static void main(String[] args) {Duck duck=new MallarDuck();Turkey turkey=new WildTurkey();Duck turkeyAdapter=new TurkeyAdapter(turkey);System.out.println("火鸡说:");turkey.gobble();turkey.fly();System.out.println("\n鸭子说:");testDuck(duck);System.out.println("\n火鸡适配器说:");testDuck(turkeyAdapter);}static void testDuck(Duck duck){duck.quack();duck.fly();}
}
代码运行结果如下:
带中国的插头出国,必须准备一个转接头(adapter)