• 第二节:类适配器模式


    一、类适配器模式

      基本介绍:

        Adapter类、通过继承 src 类、实现 dst 类接口,完成 src -> dst的适配。

    二、类适配器应用实例

      1、应用实例说明

        以生活充电器的例子来学习适配器,充电器本身相当于 Adapter,220V 交流电相当于 src(即被适配者),我们的目的 dst(目标)是 5V 直流电。

      2、思路分析

        

      3、代码实现

        src 类:

     1 /**
     2  * 被适配的类
     3  */
     4 public class Voltage220V {
     5 
     6     /**
     7      * 输出 220V 的电压
     8      * @return
     9      */
    10     public int output220V() {
    11         int src = 220;
    12         System.out.println("电压=" + src + "伏");
    13         return src;
    14     }
    15 }

        适配接口:

     1 /**
     2  * 适配接口
     3  */
     4 public interface IVoltage5V {
     5 
     6     /**
     7      * 输出 5V 电压
     8      * @return
     9      */
    10     public int output5V();
    11 }

        Adapter 适配器类:

     1 /**
     2  * 适配器 类
     3  */
     4 public class VoltageAdapter extends Voltage220V implements IVoltage5V{
     5     @Override
     6     public int output5V() {
     7         //获取到 220V 电压
     8         int srcV = output220V();
     9         //降压,转成 5V
    10         int destV = srcV / 44;
    11 
    12         return destV;
    13     }
    14 }

      

        使用端:

     1 public class Phone {
     2 
     3     /**
     4      * 充电
     5      * @param voltage5V
     6      */
     7     public void charging(IVoltage5V voltage5V) {
     8         if (voltage5V.output5V() == 5) {
     9             System.out.println("电压为5伏特,可以充电~~");
    10         } else if (voltage5V.output5V() > 5) {
    11             System.out.println("电压过高,无法充电~~");
    12         }
    13     }
    14 }
    15 -----------------------------------------------
    16 /**
    17  * 类适配器 测试
    18  */
    19 public class Client {
    20     public static void main(String[] args) {
    21         System.out.println("~~~类适配器模式~~~");
    22         Phone phone = new Phone();
    23         phone.charging(new VoltageAdapter());
    24     }
    25 }

    三、类适配器模式注意事项和细节

      1、Java 是单继承机制,所以类适配器需要继承  src 类这一点算是一个缺点,因为这要 dst 必须是接口,有一定局限性;

      2、src 类的 方法在 Adapter 中都会暴露出来,也增加了使用的成本;

      3、由于其继承了 src 类,所以它可以根据需求重写 src 类的方法,使得 Adapter 的灵活性增强了。

     

  • 相关阅读:
    【splunk】数据输入-文件目录 导入失败
    【linux】tar压缩不包含路径
    【python】已安装模块提示ImportError: No module named
    【splunk】用正则表达式提取字段
    【python】xsspider零碎知识点
    【scrapy】资料
    【splunk】一些查询例子
    【docker】将容器中数据拷贝到主机
    【linux】ubuntu下crontab无效解决方法
    Flink – metrics V1.2
  • 原文地址:https://www.cnblogs.com/niujifei/p/14289056.html
Copyright © 2020-2023  润新知