适配器模式将某个类的接口转换成客户端期望的另一个接口表示,目的是消除由于接口不匹配所造成的类的兼容性问题。适配器模式主要分为2种实现:1.继承待适配类实现目标接口、2.复合待适配类实现目标接口。
1.1、继承待适配类实现目标接口
有一个待适配的Source类,目标接口是Targetable。通过Adapter类,将Source的功能扩展到Targetable里。
package com.model.structure;public class Source { public void method1() { System.out.println("this is original method!"); } }
package com.model.structure;public interface Targetable { /* 与原类中的方法相同 */ public void method1(); /* 新类的方法 */ public void method2();}
适配器类:
package com.model.structure;public class Adapter extends Source implements Targetable { public void method2() { System.out.println("this is the targetable method!"); }}
package com.model.structure;public class AdapterTest { public static void main(String[] args) { Targetable target = new Adapter(); target.method1(); target.method2(); }}
AdapterTest的运行结果:
1.2、复合待适配类实现目标接口
不继承Source类,而是持有Source类的实例。
package com.model.structure;public class Source { public void method1() { System.out.println("this is original method!"); } }
package com.model.structure;public interface Targetable { /* 与原类中的方法相同 */ public void method1(); /* 新类的方法 */ public void method2();}
适配器类:
package com.model.structure;public class Wrapper implements Targetable { private Source source; public Wrapper(Source source) { super(); this.source = source; } @Override public void method2() { System.out.println("this is the targetable method!"); } @Override public void method1() { source.method1(); }}
package com.model.structure;public class AdapterTest { public static void main(String[] args) { Source source = new Source(); Targetable target = new Wrapper(source); target.method1(); target.method2(); }}
运行结果: