public class Source { public void method1() { System.out.println("我是类Source的方法!"); } } public interface Targetable { /* 与原类中的方法相同 */ public void method1(); /* 新类的方法 */ public void method2(); }
1 2 3 4 5 6 7
public class Adapter extends Source implements Targetable { @Override public void method2() { System.out.println("我是适配器Adapter重写接口Targetable的方法!"); } }
1 2 3 4 5 6 7 8
public class AdapterTest { public static void main(String[] args) { //多态 Targetable target = new Adapter(); target.method1(); target.method2(); } }
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(); } }
1 2 3 4 5 6 7 8
public class AdapterTest { public static void main(String[] args) { Source source = new Source(); Targetable target = new Wrapper(source); target.method1(); target.method2(); } }