适配器模式
在类Source里有一个已存在的方法sourceMethod(),现在有一个接口Target想通过一个适配器Adapter类来调用sourceMethod方法:
1.Source类
1 public class Source { 2 public void sourceMethod(){ 3 System.out.println("Source Method..."); 4 } 5 }
2.target接口
1 public interface Target { 2 public void sourceMethod(); 3 public void otherMethod(); 4 }
3.Adapter适配器类
1 public class Adapter implements Target{ 2 3 private Source source; 4 5 public Adapter(Source source){ 6 this.source = source; 7 } 8 9 @Override 10 public void sourceMethod() { 11 // TODO Auto-generated method stub 12 source.sourceMethod(); 13 } 14 15 @Override 16 public void otherMethod() { 17 // TODO Auto-generated method stub 18 System.out.println("otherMethod..."); 19 } 20 21 }
4.测试类
1 public class Test { 2 public static void main(String[] args) { 3 Target target = new Adapter(new Source()); 4 target.sourceMethod(); 5 target.otherMethod(); 6 } 7 }