spring与设计模式之四适配器模式

一、定义

适配器模式-或者称为转接口模式,变压器模式。通过适配,可以让原来提供特定功能的对象完成另外一个标准的功能。

所以,所谓的适配应该可以这样称呼:让某些类/接口适配/转换某个标准/功能。

适配器器的重点是适配,就是新增(装饰)。

为了便于记忆和理解,读者最好根据自己的习惯来命名即可,例如变压器模式。

为什么要用适配器模式?  这是因为不想大动干戈。

例如实际生活中,电厂不太可能为千家万户提供不同的电压,把电厂的电压转为需要的电压应该更加实际一些。

如果一个工厂的供电来源有多种,那么只要购买多个变压器即可,可以把不同的电源转为特定要求的电。

二、经典代码

package study.base.designPattern.adapter;

/**
 * 超级女孩的中国妇女适配器。通过这个适配器,中国妇女也是超级英雄
 * @author lzfto
 *
 */
public class SuperWomanChineseWomenAdpater implements ISuperWoman {
    
    private ChineseWoman mother;

    @Override
    public void learn() {
        if (mother==null) {
            mother=new ChineseWoman();
        }
        
        mother.study();
    }

    @Override
    public void fight() {
        if (mother==null) {
            mother=new ChineseWoman();
        }
        mother.talk();
        mother.work();
    }

}

这是经典的适配器的实现:

  1. 在适配器内部定义一个提供提供功能对象(也可以不定义)
  2. 适配器必须实现特定的接口

 

三、spring中HandlerAdapter有关代码

晚上文章很多,所以不再上太多的代码了,先理解下spring的分发器和适配器的关系图。

https://blog.csdn.net/zxd1435513775/article/details/103000992

以控制器方法为例子,所有的控制器都是接收特定的请求,然后返回特性信息(也可以不返回),所以所有的控制器方法具有共性的。

 

 下图是HanlderAdpter的类层次关系图:

 

spring的适配器模式其实没有什么特别值得说的,

默认情况下org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport会定义多个适配器。

    @Bean
    public HandlerFunctionAdapter handlerFunctionAdapter() {
        HandlerFunctionAdapter adapter = new HandlerFunctionAdapter();

        AsyncSupportConfigurer configurer = getAsyncSupportConfigurer();
        if (configurer.getTimeout() != null) {
            adapter.setAsyncRequestTimeout(configurer.getTimeout());
        }
        return adapter;
    }
@Bean
    public HttpRequestHandlerAdapter httpRequestHandlerAdapter() {
        return new HttpRequestHandlerAdapter();
    }

 

posted @ 2024-01-14 18:51  正在战斗中  阅读(53)  评论(0编辑  收藏  举报