适配器模式将某个类的接口转换成客户端期望的另一个接口表示,目的是消除由于接口不匹配所造成的类的兼容性问题。主要分为三类:类的适配器模式、对象的适配器模式、接口的适配器模式。
1. 我们来看看类的适配器模式
从图中可以看到TargetAdapterServiceImpl继承SourceServiceImpl实现了ITargetService 通过TargetAdapterServiceImpl使得ITargetService拥有了SourceServiceImpl的方法2
代码:
ITargetService:
1 /** 2 * @author wushe 3 */ 4 public interface ITargetService { 5 /** 6 * 方法2 7 */ 8 void method1(); 9 10 /** 11 * 方法2 12 */ 13 void method2(); 14 }
SourceServiceImpl:
@Service public class SourceServiceImpl { public void method1(){ System.out.println("method1"); } }
TargetAdapterServiceImpl:
@Service public class TargetAdapterServiceImpl extends SourceServiceImpl implements ITargetService { @Override public void method2() { System.out.println("method2"); } }
2. 对象的适配器模式
基本思路和类的适配器模式相同,只是将Adapter类作修改,这次不继承Source类,而是持有Source类的实例,以达到解决兼容性的问题。
区别仅仅是将TargetAdapterServiceImpl 本继承修改成注入对象调用
1 @Service 2 public class TargetAdapterServiceImpl implements ITargetService { 3 @Autowired 4 private SourceServiceImpl sourceService; 5 @Override 6 public void method1() { 7 sourceService.method1(); 8 } 9 @Override 10 public void method2() { 11 System.out.println("method2"); 12 } 13 }
3. 适配器模式是接口的适配器模式,接口的适配器是这样的:有时我们写的一个接口中有多个抽象方法,当我们写该接口的实现类时,必须实现该接口的所有方法,这明显有时比较浪费,因为并不是所有的方法都是我们需要的,有时只需要某一些,此处为了解决这个问题,我们引入了接口的适配器模式,借助于一个抽象类,该抽象类实现了该接口,实现了所有的方法,而我们不和原始的接口打交道,只和该抽象类取得联系,所以我们写一个类,继承该抽象类,重写我们需要的方法就行。
ITargetService 有方法1 与方法2
通过抽象类把方法1 与 2重写,然后SourceServiceImpl继承抽象类重写方法1
AbstractTargetAdapterServiceImpl:
1 @Component 2 public abstract class AbstractTargetAdapterServiceImpl implements ITargetService { 3 4 @Override 5 public void method1(){ 6 System.out.println("AbstractTargetAdapterServiceImpl method1"); 7 } 8 9 @Override 10 public void method2() { 11 System.out.println("AbstractTargetAdapterServiceImpl method2"); 12 } 13 14 15 }
SourceServiceImpl:
1 @Service 2 public class SourceServiceImpl extends AbstractTargetAdapterServiceImpl { 3 @Override 4 public void method1(){ 5 System.out.println("SourceServiceImpl method1"); 6 } 7 }