/** * 客户须要的接口 */ public interface Target { void request(); } /** * 被适配的类 */ public class Adaptee { public void adapteeRequest () { System.out.println("被适配者的方法"); } } /** * 适配器,继承了被适配的类,而且实现了Target定义的接口 */ public class Adapter extends Adaptee implements Target { @Override public void request() { //todo... System.out.println("适配后----"); super.adapteeRequest(); //todo... } }
/** * 测试类 */ public class Test { public static void main(String[] args) { Adaptee adaptee = new Adaptee(); adaptee.adapteeRequest(); Target adapterTarget = new Adapter(); adapterTarget.request(); } }
被适配者的方法 适配后---- 被适配者的方法
/** * 客户端应用放使用的接口 */ public interface Target { void request(); } /** * 被适配的类 */ public class Adaptee { public void adapteeRequest () { System.out.println("被适配者的方法"); } } /** * 适配器模式 */ public class Adapter implements Target { /** * 组合了被适配的类,这里能够经过set方式注入 */ private Adaptee adaptee = new Adaptee(); @Override public void request() { //todo... System.out.println("适配后----"); adaptee.adapteeRequest(); //todo... } }
/** * 应用测试类 */ public class Test { public static void main(String[] args) { Adaptee adaptee = new Adaptee(); adaptee.adapteeRequest(); Target adapterTarget = new Adapter(); adapterTarget.request(); } }
被适配者的方法 适配后---- 被适配者的方法
从上面两种状况能够看出,适配器模式一共有三个角色html
笔记本的插头为三项电,而现有的插座是两项的,须要适配器来进行适配,下面分别进行两种方式的实现。
/** * 三项插座接口 * @author Administrator * */ public interface ThreePlugIf { //使用三项电流供电 void powerWithThree(); } /** * 二项电插座 */ public class GBTowPlug { //使用二项电流供电 public void powerWithTwo () { System.out.println("使用二项电流供电"); } } /** * 笔记本类 */ public class NoteBook { private ThreePlugIf plug; /** * 只接收使用三项电充电 * @param plug */ public NoteBook (ThreePlugIf plug) { this.plug = plug; } /** * 使用插座充电 */ public void charge () { plug.powerWithThree(); } }
/** * 采用继承方式的插座适配器 * @author Administrator */ public class TwoPlugAdapterExtends extends GBTowPlug implements ThreePlugIf { public void powerWithThree() { System.out.println("借助继承适配器"); this.powerWithTwo(); } }
/** * 测试与应用类 */ public class AdapterTest { public static void main(String[] args) { ThreePlugIf three = new TwoPlugAdapterExtends(); NoteBook book = new NoteBook(three); book.charge(); } }
借助继承适配器 使用二项电流供电
/** * 二项插座转三项插座的适配器 */ public class TwoPlugAdapter implements ThreePlugIf { /** * 组合 */ private GBTowPlug plug; public TwoPlugAdapter (GBTowPlug plug) { this.plug = plug; } public void powerWithThree() { System.out.println("经过转化"); plug.powerWithTwo(); } }
/** * 测试与应用类 */ public class AdapterTest { public static void main(String[] args) { GBTowPlug two = new GBTowPlug(); ThreePlugIf three = new TwoPlugAdapter(two); NoteBook book = new NoteBook(three); book.charge(); } }
对象适配器-经过转化 使用二项电流供电
适配器模式和外观模式java
慕课网设计模式精讲
: https://coding.imooc.com/class/270.html 设计模式:适配器模式
: http://www.javashuo.com/article/p-nzylqhic-bt.html