适配器模式:适配器模式能让原本接口不匹配的类变得能够一起工作。也就是说,适配器将一个类的接口变成客户端所期望的另外一个接口。
Target:客户端需要的接口
Adaptee:已经实现的类的接口
Adapter:适配器
类适配器(继承):
1 public interface Target 2 { 3 public void request(); 4 } 5 6 public class Adaptee 7 { 8 public void achievedRequest() 9 { 10 System.out.println("Actuall business logic."); 11 } 12 } 13 14 public class Adapter extends Adaptee implements Target 15 { 16 @Override 17 public void request() 18 { 19 this.achievedRequest(); 20 } 21 } 22 23 public class Test 24 { 25 public static void main(String[] args) 26 { 27 Adapter adapter = new Adapter(); 28 adapter.request(); 29 } 30 }
对象适配器(依赖注入):
1 public interface Target 2 { 3 public void request(); 4 } 5 6 public class Adaptee 7 { 8 public void achievedRequest() 9 { 10 System.out.println("Actuall business logic."); 11 } 12 } 13 14 public class Adapter implements Target 15 { 16 private Adaptee adaptee; 17 18 public Adapter(Adaptee adaptee) 19 { 20 this.adaptee = adaptee; 21 } 22 23 @Override 24 public void request() 25 { 26 adaptee.achievedRequest(); 27 } 28 } 29 30 public class Test 31 { 32 public static void main(String[] args) 33 { 34 Adapter adapter = new Adapter(new Adaptee()); 35 adapter.request(); 36 } 37 }