结构型 之 适配器模式

定义

把一个类的接口变换成客户端所期待的另一种接口,从而是原本因接口不匹配而无法在一起工作的两个类能够一起工作。

分类

类适配器、对象适配器、接口适配器。

应用场景

实际项目开发过程中,每个人都会各自写自己的业务服务类,如ExcelImportServiceImpl、CaculateServiceImpl、ExcelExportServiceImpl。各个业务服务类都是独自写各自的服务方法,这些业务服务类都有各自的接口。现在这些业务服务类要被多线程统一调用,线程服务类接口是IThreadService,如何通过接口doBusiness()方法实现统一调用各个业务服务类。

解决方案:由于各个业务服务类的方法都是不规则的,因此需要为各个服务类分别定义一个适配器类Adapter,适配器继承业务服务类并且实现线程服务类,通过调用适配器类实现间接的调用各个业务服务类。

1.类适配器

当客户在接口中定义了他期望的行为时,我们就可以应用适配器模式,提供一个实现该接口的类,并且扩展已有的类,通过创建子类来实现适配。

目标类Target

/**
 * 业务服务类接口,在适配器模式中也称为目标类
 */
public interface IExcelImportService {
    RspDto  execute();
}
 
public class ExcelImportServiceImpl implements IExcelImportService {
    public RspDto execute() {
        System.out.println("导入Excel文件");
        return null;
    }

客户端Client接口,也是调用者

public interface IThreadService {
    RspDto  doBusiness();
}

适配器

public class ExcelImportServiceAdapter extends ExcelImportServiceImpl implements IThreadService {
   @Override
    public RspDto doBusiness() {
       execute();
    }
}

测试代码

public class Test  {
    public static void main(String[] args){
        IThreadService service = new ExcelImportServiceAdapter();
        service.doBusiness();
    }
}

2.对象适配器

/**
 * 业务服务类接口,在适配器模式中也称为目标类
 */
public interface IExcelImportService {
    RspDto  execute();
}
 
public class ExcelImportServiceImpl implements IExcelImportService {
    public RspDto execute() {
        System.out.println("导入Excel文件");
        return null;
    }
}
 
public interface IThreadService {
    RspDto  doBusiness();
}
 
/**
 * Adapter中添加一个属性保存服务类对象
 */
public class ExcelImportServiceAdapter implements IThreadService {
private IExcelImportService excelImportService ;
public ExcelImportServiceAdapter(IExcelImportService excelImportService){
       this.excelImportService = excelImportService;
}
   @Override
    public RspDto doBusiness() {
      excelImportService.execute();
    }
}
 
//测试
public class Test  {
    public static void main(String[] args){
        ExcelImportServiceImpl excelImportService = new ExcelImportServiceImpl();
        IThreadService service = new ExcelImportServiceAdapter(excelImportService );
        service.doBusiness();
    }
}

3.接口适配器

 1 public interface A  {
 2    void a();
 3    void b();
 4    void c();
 5    void d();
 6 }
 7  
 8 public class AbstractA implements  A{
 9     @Override
10     public void a() {}
11     @Override
12     public void b() {}
13     @Override
14     public void c() {}
15     @Override
16     public void d() {}
17 }
18  
19 public class AdapterB extends  AbstractA{
20     @Override
21     public void a() {
22         System.out.println("AdapterB 只需要关注a()方法");
23     }
24 }
25  
26 public class AdapterC extends  AbstractA{
27     @Override
28     public void b() {
29         System.out.println("AdapterC 只需要关注a()方法");
30     }
31 }
原文地址:https://www.cnblogs.com/walixiansheng/p/9562653.html