适配器模式
  2Vtxr3XfwhHq 2023年11月01日 54 0

适配器模式

基本介绍

  • 1.适配器模式(Adapter Pattern)将某个类的接口(方法)转换成客户期望的另一个接口(方法)表示,主要目的是兼容性,让原本因为方法不匹配的,不能一起工作的两个类可以协同工作。别名叫包装器(Wrapper)。
  • 2.适配器模式属于结构模式。
  • 3.主要有三种形式,类适配器模式,对象适配器模式,接口适配器模式。

类适配器模式

介绍

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

应用实例
  • 1.以手机充电为例,充电器本身相当于Adapter类,220V的交流电相当于src(被适配者),我们的dest(目标)是5V直流电。
  • 2.类图
代码

案例只是展示这种思想,无实际意义。

public class Voltage220V {

    public int output220V(){
        int voltage = 220;
        System.out.println("电压" + voltage + "V");
        return voltage;
    }
}
public interface Voltage5V {
    public int output5V();
}
public class Adapter extends Voltage220V implements Voltage5V{
    @Override
    public int output5V() {
        int src = this.output220V();
        int dest = src / 44;//转成5v
        return dest;
    }
}
public class Phone {

    public void charging(Voltage5V v){
        if(v.output5V() == 5){
            System.out.println("电压为5V,可以充电");
        }else if(v.output5V() > 5){
            System.out.println("电压大于5V,不能充电");
        }
    }
}
//测试
public class Client {
    public static void main(String[] args) {
        System.out.println("类适配器模式");
        new Phone().charging(new Adapter());
    }
}
注意事项和细节
  • 1.Java是单继承机制,所以类适配器需要继承src类这一点是一个缺点,还要求dest必须是接口,有一定局限性。
  • 2.Adapter类,会继承src类的所有方法,增加了使用成本。
  • 3.由于继承了src类,所以它可以根据需求重写src类的方法,使得Adapter类的灵活性增强了。

对象适配器模式

介绍
  • 1.基本思路和类的适配器模式相同,只是将Adapter类做修改,不是继承src类,而是持有src类的实例,解决兼容性的问题。即持有src类,实现dest接口,完成src -> dest的适配。
  • 2.根据合成复用原则,尽量使用关联关系替代继承关系。
  • 3.对象适配器模式是适配器模式常用的一种。
应用实例

用对象适配器模式,完成手机充电案例

public class Voltage220V {
    public int output220V(){
        int voltage = 220;
        System.out.println("输出电压" + voltage + "V");
        return voltage;
    }
}
public interface Voltage5V {
    public int output5V();
}
public class Phone {
    public void charging(Voltage5V v){
        if(v.output5V() == 5){
            System.out.println("电压为5V,可以充电");
        }else if(v.output5V() > 5){
            System.out.println("电压大于5V,不能充电");
        }
    }
}
public class Adapter implements Voltage5V {

    private Voltage220V voltage220V;

    public Adapter(){}

    public Adapter(Voltage220V voltage220V){
        this.voltage220V = voltage220V;
    }

    public void setVoltage220V(Voltage220V voltage220V) {
        this.voltage220V = voltage220V;
    }

    @Override
    public int output5V() {
        int src = voltage220V.output220V();
        int dest = src / 44;
        System.out.println("进行电压适配" + src + "->" + dest);
        return dest;
    }
}
public class Client {
    public static void main(String[] args) {
        System.out.println("对象适配器模式");
        Phone phone = new Phone();
        Adapter adapter = new Adapter(new Voltage220V());
        phone.charging(adapter);
    }
}
注意事项和细节
  • 1.对象适配器和类适配器是同一种思想,只是实现方式不同。根据合成复用原则,使用组合代替继承,所以它解决了类适配器必须继承src的局限性问题,也不再要求dest是接口。
  • 2.使用成本更低,更灵活。

接口适配器模式

介绍
  • 1.当不需要全部实现接口提供的方法时,可以设计一个抽象类实现接口,并为该接口中每个方法提供一个默认的实现(空方法),那么该抽象类的子类可以有选择性的重写某些方法。
  • 2.适用于一个接口不想使用其所有方法的情况
  • 3.接口适配器模式,也被称为默认适配器模式。
应用实例
  • 1.Android中的属性动画ValueAnimator类可以通过addListener(AnimatorListener listener)方法添加监听器,常规方法如下右图。
  • 2.不想实现Animator.AnimatorListener接口的全部方法,我们只想监听onAnimationStart 如下 下图写。
  • 3.AnimatorListenerAdapter类,就是一个接口适配器,代码如下 右图。
  • 4.AnimatorListener是一个接口。
  • 5.程序里的匿名内部类就是AnimatorListener的具体实现类。
    Java中的匿名内部类,类似接口适配器模式。

适配器模式在SpringMVC中的源码分析

  • 1.SpringMVC中的HandlerAdapter,就是用了适配器模式。
  • 2.使用HandlerAdapter的原因分析。Handler(controller,处理器)的类型不同,有多重实现方式,那么调用方式就不是确定的,如果需要直接调用Controller方法,需要调用时,就要使用很多的if else分支语句,进行判断,哪一种子类执行。这样的写法,如果要扩展controller,就要修改原来的代码,违背了ocp。
  • 3.代码分析
//DispatchServlet类中得doDispatch(HttpServletRequest request, HttpServletResponse response)方法 部分源码
HttpServletRequest processedRequest = request;
HandlerExecutionChain mappedHandler = null;//参数定义
// Determine handler for the current request.
mappedHandler = getHandler(processedRequest);//根据请求获取 对应的HandlerExecutionChain
if (mappedHandler == null) {
   noHandlerFound(processedRequest, response);
   return;
}

// Determine handler adapter for the current request.
HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler());//根据handler获取对应的HandlerAdapter

//getHandlerAdapter源码 遍历所有的HandlerAdapter 判断是否支持当前handler,支持返回对应的HandlerAdapter
protected HandlerAdapter getHandlerAdapter(Object handler) throws ServletException {
		if (this.handlerAdapters != null) {
			for (HandlerAdapter ha : this.handlerAdapters) {
				if (logger.isTraceEnabled()) {
					logger.trace("Testing handler adapter [" + ha + "]");
				}
				if (ha.supports(handler)) {
					return ha;
				}
			}
		}
		throw new ServletException("No adapter for handler [" + handler +
				"]: The DispatcherServlet configuration needs to include a HandlerAdapter that supports this handler");
}
  • 4.HandlerAdapter接口中的方法
boolean supports(Object handler);//判断是否支持当前handler
//执行handler
@Nullable
ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception;
long getLastModified(HttpServletRequest request, Object handler);
  • 5.HandlerAdapter及其子类
  • 6.简单模拟写一下适配器模式,及其对应的controller源码
/**
 * @author 长名06
 * @version 1.0
 * Controller接口
 */
public interface Controller {

}

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

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

class AnnotationController implements Controller{
    public void doAnnotationController(){
        System.out.println("annotation...");
    }
}
/**
 * @author 长名06
 * @version 1.0
 * 适配器接口
 * 一个controller对应一个handlerAdapter
 */
public interface HandlerAdapter {

    //判断handler是否是当前适配器对应的controller
    boolean supports(Object handler);

    void handle(Object handler);
}

class HttpHandlerAdapter implements HandlerAdapter{
    @Override
    public boolean supports(Object handler) {
        return (handler instanceof HttpController);
    }

    @Override
    public void handle(Object handler) {
        ((HttpController) handler).doHttpController();
    }
}

class SimpleHandlerAdapter implements HandlerAdapter{
    @Override
    public boolean supports(Object handler) {
        return (handler instanceof SimpleController);
    }

    @Override
    public void handle(Object handler) {
        ((SimpleController) handler).doSimpleController();
    }
}

class AnnotationHandlerAdapter implements HandlerAdapter{
    @Override
    public boolean supports(Object handler) {
        return (handler instanceof AnnotationController);
    }

    @Override
    public void handle(Object handler) {
        ((AnnotationController) handler).doAnnotationController();
    }
}
/**
 * @author 长名06
 * @version 1.0
 * 适配器模式
 */
public class Dispatch {

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

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

    public void doDispatch(){
//        HttpController controller = new HttpController();
//        SimpleController controller = new SimpleController();
        AnnotationController controller = new AnnotationController();
        HandlerAdapter adapter = getHandler(controller);
        adapter.handle(controller);
    }

    public HandlerAdapter getHandler(Controller controller){
        for(HandlerAdapter ha : this.handlerAdapters){
            if(ha.supports(controller)){
                return ha;
            }
        }
        return null;
    }

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

注意事项和细节

  • 1.三种形式,按照src以怎样的方式给到Adapter(在Adapter里的形式)命名的
  • 2.类适配器:以类给到,在Adapter里,就是将src当作类,继承;对象适配器:以对象给到 ,在Adapter里,将src作为一个对象持有;接口适配器:以接口给到,在Adapter里,将src作为一个接口,实现。
  • 3.Adapter模式最大的作用就是将原本不兼容的接口融合在一起工作。
  • 4.实际开发中,不一定非要按照这三种要求,重要的是其思想

只是为了记录自己的学习历程,且本人水平有限,不对之处,请指正。

【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月08日 0

暂无评论

推荐阅读
  ZkZ4n0nvAySz   2024年04月14日   44   0   0 设计模式
  bWqO7ATbLQET   2024年03月08日   74   0   0 设计模式
  ZkZ4n0nvAySz   2024年04月16日   48   0   0 设计模式
  ZkZ4n0nvAySz   2024年04月15日   69   0   0 设计模式
  bVJlYTdzny4o   2024年04月30日   55   0   0 设计模式
  ZkZ4n0nvAySz   2024年04月13日   68   0   0 设计模式
  Thv3NVnh1dDs   2024年02月19日   142   0   0 设计模式
2Vtxr3XfwhHq