深入浅出细说结构型设计模式--适配器(Adapter)模式

186 阅读2分钟

「这是我参与11月更文挑战的第1天,活动详情查看:2021最后一次更文挑战

前言

 大家好,我是程序猿小白 GW_gw,很高兴能和大家一起学习进步。

以下内容部分来自于网络,如有侵权,请联系我删除,本文仅用于学习交流,不用作任何商业用途。

摘要

 本文主要介绍结构型设计模式的适配器模式。

适配器模式(Adapter)

提到适配器我们首先想到的就是笔记本电脑的适配器,它把电源的交流电转换为笔记本电脑需要的直流电,适配器模式实现的也就是这种功能。

适配器模式:将一个类的接口转换为客户需要的另一个接口,使原来由于接口不兼容而不能一起工作的类能一起工作。分为类结构模式和对象结构模式,前者应用较少。

适配器模式有三个主要角色:

  • 适配器类(Adapter):中间转换器,把适配者接口转换成目标接口。使得用户能够按照目标接口的方式使用适配者。就好像笔记本电脑使用的是直流电,但直流电实际是交流电经过适配器转换而来的。
  • 目标接口(Target):客户需要的接口(直流电)。
  • 适配器接口(Adaptee):被访问和适配的现存组件库中的组件接口(交流电)

类适配器实现代码:

 //目标接口
 public interface Target {
     /**
      * Methods required by the client
      */
     public void request();
 }
 //适配者接口
 public class Adaptee {
     public void specificRequest(){
         System.out.println("The component that the client actually calls!");
     }
 }
 //适配器
 public class Adapter extends Adaptee implements Target{
     @Override
     public void request() {
         specificRequest();
     }
 }
 //Test
 public class AdapterTest {
     public static void main(String[] args) {
         Target target = new Adapter();
         target.request();
     }
 }

对象适配器实现代码:

 //目标接口
 public interface Target {
     /**
      * Methods required by the client
      */
     public void request();
 }
 //适配者接口
 public class Adaptee {
     public void specificRequest(){
         System.out.println("The component that the client actually calls!");
     }
 }
 //对象适配器类:
 public class ObjectAdapter implements Target{
     /**
      * Combination of object
      */
     private Adaptee adaptee;
     public ObjectAdapter(Adaptee adaptee){
         this.adaptee = adaptee;
     }
     @Override
     public void request(){
         adaptee.specificRequest();
     }
 }
 //Test
 public class ObjectAdapterTest {
     public static void main(String[] args) {
         Adaptee adaptee = new Adaptee();
         Target target = new ObjectAdapter(adaptee);
         target.request();
     }
 }

UML图

image.png

结语

以上就是我对适配器模式的一些浅见,希望对读者有所帮助,如有不正之处,欢迎掘友们批评指正。