设计模式-适配器模式

将一个类的接口转换成另一种接口,让原本接口不兼容的类可以兼容,其别名为包装器(Wrapper)

  • 被适配者:需要被适配的类、接口、对象,简称src(即不同国家使用的不同口的插座)
  • 适配器(Adapter):即插口转换器,用于将不同数量的插口统一成三角形插座
  • 目标:最终需要的输出,简称dst(即需要的三角形插座)

假设拿一个充电器给手机充电:充电器即Adapter,220V交流电为src,5V直流电为dst


1.类适配器模式

1.1 基本介绍

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

在这里插入图片描述

1.2 代码实现
// 被适配的类
public class Voltage220V {
    // 输出220V的电压
    public int output220V() {
        int src = 220;
        System.out.println("电压=" + src + "伏");
        return src;
    }
}
// 适配接口
public interface IVoltage5V {
    int output5V();
}
// 适配器类
public class VoltageAdapter extends Voltage220V implements IVoltage5V {
    @Override
    public int output5V() {
        int srcV = output220V();  // 获取到220V电压
        int dstV = srcV / 44 ;  // 转成 5v
        return dstV;
    }
}
public class Phone {
    // 充电
    public void charging(IVoltage5V iVoltage5V) {
        if(iVoltage5V.output5V() == 5) {
            System.out.println("电压为5V, 可以充电~~");
        } else if (iVoltage5V.output5V() > 5) {
            System.out.println("电压大于5V, 不能充电~~");
        }
    }
}
public class Client {
    public static void main(String[] args) {
        System.out.println(" === 类适配器模式 ====");
        Phone phone = new Phone();
        phone.charging(new VoltageAdapter());
    }
}
1.3 优缺点
  • 类适配器需要继承src类并使用其中的方法,增加了使用成本
  • 可根据需求重写src类的方法,增强Adapter的灵活性

2.对象适配器模式

2.1 基本介绍

Adapter通过持有src类,实现dst类接口,完成src->dst的适配(用关联关系来替代继承关系)

在这里插入图片描述

2.2 代码实现
// 被适配的类
public class Voltage220V {
    // 输出220V的电压
    public int output220V() {
        int src = 220;
        System.out.println("电压=" + src + "伏");
        return src;
    }
}
// 适配接口
public interface IVoltage5V {
    int output5V();
}
// 适配器类
public class VoltageAdapter implements IVoltage5V {  // 少了继承

    private Voltage220V voltage220V; // 关联关系之聚合
    
    // 通过构造器,传入一个Voltage220V实例
    public VoltageAdapter(Voltage220V voltage220v) {
        this.voltage220V = voltage220v;
    }

    @Override
    public int output5V() {
        int dst = 0;
        if(null != voltage220V) {
            int src = voltage220V.output220V();  // 获取220V电压
            System.out.println("使用对象适配器,进行适配~~");
            dst = src / 44;
            System.out.println("适配完成,输出的电压为=" + dst);
        }
        return dst;
    }
}
public class Phone {
    // 充电
    public void charging(IVoltage5V iVoltage5V) {
        if(iVoltage5V.output5V() == 5) {
            System.out.println("电压为5V, 可以充电~~");
        } else if (iVoltage5V.output5V() > 5) {
            System.out.println("电压大于5V, 不能充电~~");
        }
    }
}
public class Client {
    public static void main(String[] args) {
        System.out.println(" === 对象适配器模式 ====");
        Phone phone = new Phone();
        phone.charging(new VoltageAdapter(new Voltage220V()));  // 使用构造器
    }
}
2.3 优缺点
  • 解决了类适配器必须继承src的局限性问题,也不要求dst必须是接口
  • 使用成本更低,更灵活

3.接口适配器模式

3.1 基本介绍
  • 也称适配器模式或缺省适配器模式

  • 当不需要全部实现接口提供的方法时:

    • 先设计一个抽象类实现接口
    • 为该接口中每个方法提供一个默认实现(即空方法)
    • 该抽象类的子类可有选择地覆盖父类的某些方法来实现需求
  • 适用于一个接口不想使用其所有的方法的情况

3.2 代码实现
public interface Interface4 {
    void m1();
    void m2();
    void m3();
    void m4();
}
// 在AbsAdapter中将Interface4的方法进行默认实现
public abstract class AbsAdapter implements Interface4 {
    public void m1() {}
    public void m2() {}
    public void m3() {}
    public void m4() {}
}
public class Client {
    public static void main(String[] args) {
        AbsAdapter absAdapter = new AbsAdapter() {
            // 只需要去覆盖需要使用接口方法
            @Override
            public void m1() {
                System.out.println("使用了m1的方法");
            }
        };

        absAdapter.m1();
    }
}

4.SpringMVC中的使用

// 多种Controller实现
public interface Controller {}

class HttpController implements Controller {
   public void doHttpHandler() {
      System.out.println("http...");
   }
}

class SimpleController implements Controller {
   public void doSimplerHandler() {
      System.out.println("simple...");
   }
}

class AnnotationController implements Controller {
   public void doAnnotationHandler() {
      System.out.println("annotation...");
   }
}
// 定义一个Adapter接口
public interface HandlerAdapter {
    boolean supports(Object handler);

    void handle(Object handler);
}

// 多种适配器类
class SimpleHandlerAdapter implements HandlerAdapter {

   public void handle(Object handler) {
      ((SimpleController) handler).doSimplerHandler();
   }

   public boolean supports(Object handler) {
      return (handler instanceof SimpleController);
   }

}

class HttpHandlerAdapter implements HandlerAdapter {

   public void handle(Object handler) {
      ((HttpController) handler).doHttpHandler();
   }

   public boolean supports(Object handler) {
      return (handler instanceof HttpController);
   }

}

class AnnotationHandlerAdapter implements HandlerAdapter {

   public void handle(Object handler) {
      ((AnnotationController) handler).doAnnotationHandler();
   }

   public boolean supports(Object handler) {
      return (handler instanceof AnnotationController);
   }
}
public class DispatchServlet {

   public static List<HandlerAdapter> handlerAdapters = new ArrayList<HandlerAdapter>();

   public DispatchServlet() {
      handlerAdapters.add(new AnnotationHandlerAdapter());
      handlerAdapters.add(new HttpHandlerAdapter());
      handlerAdapters.add(new SimpleHandlerAdapter());
   }

   public void doDispatch() {

      // 此处模拟SpringMVC从request取handler的对象,
      // 适配器可以获取到希望的Controller
       HttpController controller = new HttpController();
      // AnnotationController controller = new AnnotationController();
      //SimpleController controller = new SimpleController();
      // 得到对应适配器
      HandlerAdapter adapter = getHandler(controller);
      // 通过适配器执行对应的controller对应方法
      adapter.handle(controller);

   }

   public HandlerAdapter getHandler(Controller controller) {
      // 遍历:根据得到的controller(handler), 返回对应适配器
      for (HandlerAdapter adapter : this.handlerAdapters) {
         if (adapter.supports(controller)) {
            return adapter;
         }
      }
      return null;
   }

   public static void main(String[] args) {
      new DispatchServlet().doDispatch(); // http...
   }

}

5.注意事项和细节

三种方式根据src以怎样的形式给到Adapter(在Adapter里的形式)命名:

  • 类适配器:以类给到,在Adapter里将src当做类(继承)
  • 对象适配器:以对象给到,在Adapter里将src作为一个对象(持有)
  • 接口适配器:以接口给到,在Adapter里将src作为一个接口(实现)

参考

https://www.bilibili.com/video/BV1G4411c7N4?p=60-65

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值