(七)结构型模式-适配器模式

itmahy
itmahy
发布于 2024-01-19 / 28 阅读
0
0

(七)结构型模式-适配器模式

适配器模式

将一个类的接口转换成客户希望的另外一个接口,使得原本由于接口不兼容而不能一起工作的那些类能一起工作。

适配的意思是适应、匹配。通俗地讲,适配器模式适用于 有相关性但不兼容的结构,源接口通过一个中间件转换后才可以适用于目标接口,这个转换过程就是适配,这个中间件就称之为适配器。

使用代码模拟利用家用电给手机充电的过程:

  • 未使用适配器,充不了电

    /**
     * @Author: mahy
     * @Contact: [email protected]
     * @Date: 2022-03-08 8:58
     * @Description: 提供家用电压
     */
    public class HomeVoltage {
    ​
        public int supplyVoltage(){
            return 220;
        }
    }
    /**
     * @Author: mahy
     * @Contact: [email protected]
     * @Date: 2022-03-08 8:59
     * @Description: 给手机充电
     */
    public class PhoneVoltage {
    ​
        public void charge(int voltage){
            if (voltage != 5){
                throw new IllegalArgumentException("只能使用5v电压进行充电");
            }
            System.out.println("正常充电");
        }
    }
    /**
     * @Author: mahy
     * @Contact: [email protected]
     * @Date: 2022-03-07 14:02
     * @Description: 测试给手机充电
     */
    public class Test001 {
    ​
        public static void main(String[] args) throws CloneNotSupportedException {
            HomeVoltage  homeVoltage = new HomeVoltage();
            int i = homeVoltage.supplyVoltage();
            PhoneVoltage phoneVoltage = new PhoneVoltage();
            phoneVoltage.charge(i);
        }
    }

从上面的结果可以看出,如果不适用适配器,无法让家用电220V给手机5V的电压提供充电服务。

  • 使用适配器充电

    • 添加一个适配器

      /**
       * @Author: mahy
       * @Contact: [email protected]
       * @Date: 2022-03-08 9:08
       * @Description: 电源适配器
       */
      public class VoltageAdapter {
      ​
          public int convert(int homeVoltage){
              return homeVoltage - 215;
          }
      }
    • 调用测试

      /**
       * @Author: mahy
       * @Contact: [email protected]
       * @Date: 2022-03-07 14:02
       * @Description: 在这儿描述
       */
      public class Test001 {
      ​
          public static void main(String[] args) throws CloneNotSupportedException {
              HomeVoltage  homeVoltage = new HomeVoltage();
              int i = homeVoltage.supplyVoltage();
      ​
              //家用电压跟手机充电电压之间添加一个适配器
              VoltageAdapter adapter  = new VoltageAdapter();
              int convert = adapter.convert(i);
      ​
              //使用适配后的电压给手机充电
              PhoneVoltage phoneVoltage = new PhoneVoltage();
              phoneVoltage.charge(convert);
          }
      }

这就是适配器模式。在我们日常的开发中经常会使用到各种各样的 Adapter,都属于适配器模式的应用。

但适配器模式并不推荐多用。因为未雨绸缪好过亡羊补牢,如果事先能预防接口不同的问题,不匹配问题就不会发生,只有遇到源接口无法改变时,才应该考虑使用适配器。比如现代的电源插口中很多已经增加了专门的充电接口,让我们不需要再使用适配器转换接口,这又是社会的一个进步。


评论