Design pattern (5) adapter pattern

Adapter mode

concept

  1. The Adapter Pattern serves as a bridge between two incompatible interfaces. This type of design pattern is a structural pattern, which combines the functions of two independent interfaces.
  2. This mode involves a single class, which is responsible for adding independent or incompatible interface functions.
  3. It converts the interface of a system into another form, so that the interface that cannot be directly called can be called.

Features

  • Source (Adaptee): The object or type that needs to be adapted, the old version or the card reader between the memory card and the notebook.
  • Adapter: The intermediate object connecting the target and the source, which is equivalent to a converter, and the old and new versions can be compatible.
  • Target: The interface that the customer expects. The target can be a concrete or abstract class, or an interface.

scenes to be used

Compatibility of new and old version interfaces.

Pros and cons

  • advantage

    1. You can let any two unrelated classes travel together.
    2. Improved reuse of classes.
    3. Increased the transparency of the class.
    4. Good flexibility.
  • Disadvantage

    1. Excessive use of adapters will make the system very messy and difficult to grasp as a whole.

The structure of the pattern

SpringMvc is a great framework with relatively flexible configuration and simple implementation. Today we will simulate the adaptation process and simple use of an adapter.

Development steps

  • Simulate SpringMvc's DispatcherServlet object to dispatch the request. We also write a doService method the same as it, as shown below:

Insert picture description here

      Inside the method, call the doDispatch method


Insert picture description here


      Pick out the only one corresponding to this request handler from all the adapter objects


Insert picture description here


      Inside the getHandlerAdapter method, call the supports method in the adapter to determine whether the request handler is supported


Insert picture description here


      What HandlerAdapter are roughly there?


Insert picture description here



      We have seen above that there is a supports method. The adapter method is defined in a unified parent class, which mainly contains two methods. Supports determine whether the corresponding handler request is supported, and

handle handles the specific The handler request, let us take a look, as shown below:



Insert picture description here


      I have also seen here that it is not difficult to achieve. Let’s start now.
      Define a processing class similar to DispatcherServlet

package com.lee.adapter.controller;

import com.lee.adapter.service.HandlerAdapter;
import com.lee.adapter.service.impl.RequestMappingHandlerAdapter;
import com.lee.adapter.service.impl.SimpleHandlerAdapter;
import com.lee.adapter.service.impl.SimpleServletHandlerAdapter;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zfl_a
 * @Desc 入口测试
 * @date 2020/8/16
 * @project springboot_design_pattern
 */
@RestController
public class DispatcherController implements InitializingBean {
    
    

    //自动装配
    @Autowired
    private Map<String,Controller> controllerMap = new HashMap<>();

    private List<HandlerAdapter> handlerAdapters = new ArrayList<>();

    /**
     * 处理
     * @param controllerName simpleController simpleServletController httpRequestController
     * @return
     */
    @GetMapping("/doService")
    public String doService(String controllerName){
    
    

        return doDispatcher(controllerName);
    }

    private String doDispatcher(String controllerName) {
    
    

        // 获取适配器 参数可根据具体的Handler替换
        Controller controller = controllerMap.get(controllerName);
        HandlerAdapter ha = getHandlerAdapter(controller);
        if(ha == null) {
    
    
            return "没有此适配器";
        }
        //具体处理
        return ha.handle(controller);
    }

    /**
     * 获取适配器
     * @param controller
     * @return
     */
    private HandlerAdapter getHandlerAdapter(Controller controller) {
    
    
        if (this.handlerAdapters != null) {
    
    
            for (HandlerAdapter ha : this.handlerAdapters) {
    
    
                if (ha.supports(controller)) {
    
    
                    return ha;
                }
            }
        }
        return null ;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
    
    

        //初始化适配器实例
        RequestMappingHandlerAdapter mappingHandlerAdapter = new RequestMappingHandlerAdapter();
        SimpleHandlerAdapter simpleHandlerAdapter = new SimpleHandlerAdapter();
        SimpleServletHandlerAdapter servletHandlerAdapter = new SimpleServletHandlerAdapter();
        handlerAdapters.add(mappingHandlerAdapter);
        handlerAdapters.add(simpleHandlerAdapter);
        handlerAdapters.add(servletHandlerAdapter);
    }
}

  • Simulation Controller request class

      Define a common Controller and do nothing

package com.lee.adapter.controller;

/**
 * @author zfl_a
 * @date 2020/8/16
 * @project springboot_design_pattern
 */
public interface Controller {
    
    
}

      Define the corresponding implementation class and do specific processing

package com.lee.adapter.controller;

import org.springframework.stereotype.Component;

/**
 * @author zfl_a
 * @date 2020/8/16
 * @project springboot_design_pattern
 */
@Component
public class HttpRequestController implements Controller {
    
    

    public String doRequestMapping(){
    
    
        return "do http request ....";
    }

}

package com.lee.adapter.controller;

import org.springframework.stereotype.Component;

/**
 * @author zfl_a
 * @date 2020/8/16
 * @project springboot_design_pattern
 */
@Component
public class SimpleController implements Controller {
    
    

    public String doSimple(){
    
    
        return "do simple ....";
    }
}

package com.lee.adapter.controller;

import org.springframework.stereotype.Component;

/**
 * @author zfl_a
 * @date 2020/8/16
 * @project springboot_design_pattern
 */
@Component
public class SimpleServletController implements Controller {
    
    

    public String doSimpleServlet(){
    
    
        return "do Simple Servlet....";
    }
}

  • Define an adapter interface with HandlerAdapter
package com.lee.adapter.service;

import org.springframework.lang.Nullable;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author zfl_a
 * @Desc 所有适配器的父类
 * @date 2020/8/16
 * @project springboot_design_pattern
 */
public interface HandlerAdapter {
    
    

    boolean supports(Object handler);

    String handle(Object handler) ;

}

  • Define the Adapter corresponding to the above Controller
package com.lee.adapter.service.impl;

import com.lee.adapter.controller.HttpRequestController;
import com.lee.adapter.service.HandlerAdapter;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author zfl_a
 * @date 2020/8/16
 * @project springboot_design_pattern
 */
public class RequestMappingHandlerAdapter implements HandlerAdapter {
    
    

    @Override
    public boolean supports(Object handler) {
    
    
        return handler instanceof HttpRequestController;
    }

    @Override
    public String handle(Object handler)  {
    
    

        return ((HttpRequestController)handler).doRequestMapping();
    }
}

package com.lee.adapter.service.impl;

import com.lee.adapter.controller.SimpleController;
import com.lee.adapter.service.HandlerAdapter;
import org.springframework.stereotype.Component;

/**
 * @author zfl_a
 * @date 2020/8/16
 * @project springboot_design_pattern
 */
public class SimpleHandlerAdapter implements HandlerAdapter {
    
    

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

    @Override
    public String handle(Object handler)  {
    
    
        return ((SimpleController)handler).doSimple();
    }
}

package com.lee.adapter.service.impl;

import com.lee.adapter.controller.SimpleServletController;
import com.lee.adapter.service.HandlerAdapter;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author zfl_a
 * @date 2020/8/16
 * @project springboot_design_pattern
 */
public class SimpleServletHandlerAdapter implements HandlerAdapter {
    
    
    @Override
    public boolean supports(Object handler) {
    
    
        return handler instanceof SimpleServletController;
    }

    @Override
    public String handle(Object handler) {
    
    

        return ((SimpleServletController)handler).doSimpleServlet();
    }
}

The test results are as follows:

  • When the request parameter is?controllerName=simpleServletController:
    Insert picture description here

  • When the request parameter is?controllerName=httpRequestController:
    Insert picture description here

All the code about the design pattern will be hosted to: the design pattern code , welcome to pay attention.

Guess you like

Origin blog.csdn.net/qq_37640410/article/details/108634765