适配器模式:将一个类的接口,转换成客户所期望的另一个接口,适配器让原本接口不兼容的类可以合作无间。
package cn.adapter.demo;
/**
* 鸭子接口:会quack叫和飞
* @author wy
*
*/
public interface Duck {
public void quack();
public void fly();
}
package cn.adapter.demo; /** * 一个fool鸭子 * @author wy * */ public class FoolDuck implements Duck { @Override public void quack() { // TODO Auto-generated method stub System.out.println("a fool duck quack..."); } @Override public void fly() { // TODO Auto-generated method stub System.out.println("a fool duck fly so far...."); } }
package cn.adapter.demo; /** * 火鸡接口:只会gooble叫,而且飞不远 * @author wy * */ public interface Turkey { public void gooble(); public void fly(); }
package cn.adapter.demo; /** * 一个野火鸡 * @author wy * */ public class WildTurkey implements Turkey { @Override public void gooble() { // TODO Auto-generated method stub System.out.println("wild turkey goggle...."); } @Override public void fly() { // TODO Auto-generated method stub System.out.println("wild turkey just can fly a short distince..."); } }火鸡适配器:
package cn.adapter.demo; /** * 一个火鸡适配器:将火鸡变成鸭子 * @author wy * */ public class TurkeyApater implements Duck { private Turkey turkey; public TurkeyApater(Turkey turkey) { this.turkey = turkey; } @Override public void quack() { // TODO Auto-generated method stub turkey.gooble(); } @Override public void fly() { // TODO Auto-generated method stub turkey.fly(); } }鸭子适配器:
package cn.adapter.demo; /** * 鸭子适配器:将鸭子变成火鸡 * @author wy * */ public class DuckApater implements Turkey { private Duck duck; public DuckApater(Duck duck) { this.duck = duck; } @Override public void gooble() { // TODO Auto-generated method stub duck.quack(); } @Override public void fly() { // TODO Auto-generated method stub duck.fly(); } }
测试:
package cn.adapter.demo; public class Test { public static void main(String[] args) { WildTurkey turkey = new WildTurkey(); TurkeyApater apater = new TurkeyApater(turkey); //让火鸡执行鸭子的动作 apater.quack(); apater.fly(); FoolDuck duck = new FoolDuck(); DuckApater duckApater = new DuckApater(duck); //让鸭子执行火鸡的动作 duckApater.gooble(); duckApater.fly(); } }