适配器模式:将一个类的接口,转换成客户期望的另外一个接口,适配器将原本接口不兼容的类可以合作无间。
意图:不改变接口,但加入责任
/** *暴露的公共接口 * Created by Administrator on 2018/1/9. */ public interface Duck { void quack(); void fly(); }
/** * 需要被适配的接口 * Created by Administrator on 2018/1/9. */ public interface Turkey { void gobble(); void fly(); }
/** * Created by Administrator on 2018/1/9. */ public class WildTurkey implements Turkey { @Override public void gobble() { System.out.println("wildturkey is gobble"); } @Override public void fly() { System.out.println("wildturkey is fly"); } }
/** * 适配器 * Created by Administrator on 2018/1/9. */ public class TurkeyAdapter implements Duck { private Turkey turkey; public TurkeyAdapter(Turkey turkey) { this.turkey = turkey; } @Override public void quack() { turkey.gobble(); //这里进行适配 } @Override public void fly() { turkey.fly(); } }
/** * Created by Administrator on 2018/1/9. */ public class TestAdapter { public static void main(String[] args) { Turkey wildTurkey = new WildTurkey(); wildTurkey.gobble(); /** * 这里进行适配 * **/ TurkeyAdapter turkeyAdapter = new TurkeyAdapter(wildTurkey); turkeyAdapter.quack(); turkeyAdapter.fly(); } }