适配器模式(Adapter Pattern)是作为两个不兼容的接口之间的桥梁。这种类型的设计模式属于结构型模式,它结合了两个独立接口的功能。
    这种模式涉及到一个单一的类,该类负责加入独立的或不兼容的接口功能。举个真实的例子,读卡器是作为内存卡和笔记本之间的适配器。您将内存卡插入读卡器,再将读卡器插入笔记本,这样就可以通过笔记本来读取内存卡。

    假设场景 手机充电需要5v的电,现在只有220v电压,需要适配器,也就是 变压器来提供电。 就是直接数据不能满足需要,需要转换数据的时候 使用.

    手机需要的是5v的电压

    1. /**
    2. * @author meikb
    3. * @desc 5伏的变压器
    4. * @date 2020-05-23 11:56
    5. */
    6. public interface Voltage5 {
    7. //提供5v的电压 输出的接口
    8. public int outPut5V();
    9. }

    现在有一个提供220v的电源

    1. /**
    2. * @author meikb
    3. * @desc 220伏的变压器
    4. * @date 2020-05-23 11:56
    5. */
    6. public class Voltage220 {
    7. //提供220v的电压 输出的接口
    8. public int outPut220V(){
    9. return 220;
    10. }
    11. }

    有5v的电压 手机才能充电

    1. /**
    2. * @author meikb
    3. * @desc
    4. * @date 2020-05-23 11:57
    5. */
    6. public class Mobile {
    7. public void charging(Voltage5 voltage5){
    8. if(5 == voltage5.outPut5V()){
    9. System.out.println("开始充电!!");
    10. }else{
    11. System.out.println("电压异常,停止充电!!");
    12. }
    13. }
    14. }

    把220v的电压 通过转换 转换成5v的电压

    1. public class VoltageAdapter implements Voltage5{
    2. public Voltage220 voltage220;
    3. VoltageAdapter(Voltage220 voltage220){
    4. this.voltage220 = voltage220;
    5. }
    6. @Override
    7. public int outPut5V() {
    8. return voltage220.outPut220V()/44;
    9. }
    10. }

    测试主函数

    1. /**
    2. * @author meikb
    3. * @desc
    4. * @date 2020-05-23 11:58
    5. */
    6. public class AdapterMain {
    7. public static void main(String[] args) {
    8. Mobile mobile = new Mobile();
    9. Voltage220 voltage220 = new Voltage220();
    10. //一般的想法 直接在这里转换成想要的数据
    11. //使用设计模式 提供一个转换类 VoltageAdapter 专门转换数据
    12. Voltage5 voltage5 = new VoltageAdapter(voltage220);
    13. mobile.charging(voltage5);
    14. }
    15. }