1.类适配
2.对象适配
3.接口适配
1.类适配
待适配的接口
package com.yun.base.design.adapter; public interface Targetable { /* 与原类中的方法相同 */ public void method1(); /* 新类的方法 */ public void method2(); }
待适配的类
package com.yun.base.design.adapter; /** * 01、类的适配器模式 * 核心思想就是:有一个Source类,拥有一个方法,待适配, * 目标接口是Targetable,通过Adapter类,将Source的功能扩展到Targetable里 * @author Administrator * */ public class Source { public void method1() { System.out.println("this is original method!"); } }
适配器
package com.yun.base.design.adapter; /** * 01、类的适配器模式 * 核心思想就是:有一个Source类,拥有一个方法,待适配, * 目标接口是Targetable,通过Adapter类,将Source的功能扩展到Targetable里 * @author Administrator * */ public class Adapter extends Source implements Targetable { @Override public void method2() { System.out.println("this is the targetable method!"); } }
2.对象适配
待适配接口 Targetable ,待适配类 Source
适配器
package com.yun.base.design.adapter; /** * 02、对象的适配器模式 基本思路和类的适配器模式相同,只是将Adapter类作修改,这次不继承Source类, * 而是持有Source类的实例,以达到解决兼容性的问题 * @author Administrator * */ 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(); } }
3.接口适配
待适配接口 Sourceable,待适配的类
抽象类
package com.yun.base.design.adapter; public abstract class Wrapper2 implements Sourceable{ public void method1(){} public void method2(){} }
实现
package com.yun.base.design.adapter; public class SourceSub1 extends Wrapper2 { public void method1(){ System.out.println("the sourceable interface's first Sub1!"); } }
package com.yun.base.design.adapter; public class SourceSub2 extends Wrapper2 { public void method2(){ System.out.println("the sourceable interface's second Sub2!"); } }
4.测试
package com.yun.base.design.adapter; public class AdapterTest { public static void main(String[] args) { //类适配 classAdapter(); //对象适配 objectAdapter(); //接口适配 interfaceAdapter(); } /** * 类适配 */ public static void classAdapter() { Targetable target = new Adapter(); target.method1(); target.method2(); } /** * 对象适配 */ public static void objectAdapter() { Source source = new Source(); Targetable target = new Wrapper(source); target.method1(); target.method2(); } /** * 接口适配 */ public static void interfaceAdapter() { Sourceable source1 = new SourceSub1(); Sourceable source2 = new SourceSub2(); source1.method1(); source1.method2(); source2.method1(); source2.method2(); } }