定义:适配器模式(Adapter Pattern)是作为两个不兼容的接口之间的桥梁。这种类型的设计模式属于结构型模式,它结合了两个独立接口的功能。
下面参照springmvc实现controller来实现一个适配器模式;
处理器Controller(HttpRequestHandler,Servlet,等等)的类型不同,有多重实现方式,那么调用方式就不是确定的,如果需要直接调用Controller方法,需要调用的时候就得不断是使用if else来进行判断是哪一种子类然后执行。那么如果后面要扩展Controller,就得修改原来的代码,这样违背了开闭原则(对修改关闭,对扩展开放)。
1 定义一个接口
public interface HandlerAdapter {
Object handle(String request, String response, Object handler) throws Exception;
}
2 做接口的两个实现,1 controller,2 servlet`
public class SimpleControllerHandlerAdapter implements HandlerAdapter {
@Override
public Object handle(String request, String response, Object handler) throws Exception {
System.out.println("调用SimpleControllerHandlerAdapter");
new Controller().handleRequest(request, response);
return null;
}
}
public class SimpleServletHandlerAdapter implements HandlerAdapter {
@Override
public Object handle(String request, String response, Object handler) throws Exception {
System.out.println("调用SimpleServletHandlerAdapter");
System.out.println("调用SimpleControllerHandlerAdapter");
new Servlet().service(request, response);
return null;
}
}
3 定义controller和servlet的处理类
public class Controller {
public Object handleRequest(String req,String resp){
System.out.println("调用了controller");
return null;
}
}
public class Servlet {
public Object service(String req,String resp){
System.out.println("调用了Servlet");
return null;
}
}
4 模仿spring 做一个DispatcherServlet
public class DispatcherServlet {
private List<HandlerAdapter> handlerAdapters;
public void init(){
handlerAdapters = new ArrayList<HandlerAdapter>();
//这里简单处理,直接new
handlerAdapters.add(new SimpleControllerHandlerAdapter());
handlerAdapters.add(new SimpleServletHandlerAdapter());
}
public void doDispatch(String request, String response) throws Exception {
for (HandlerAdapter ha : this.handlerAdapters) {
if (request.equals(ha.getClass().getName())) {
Object mv = ha.handle(request, response, "");
System.out.println("调用适配器结束");
}
}
}
}
调用
public class Test {
public static void main(String[] args) {
DispatcherServlet d = new DispatcherServlet();
d.init();
try {
d.doDispatch("com.xj.pattern.adapter.handler.SimpleServletHandlerAdapter", "");
} catch (Exception e) {
e.printStackTrace();
}
}
}
结果展示:
调用SimpleServletHandlerAdapter
调用SimpleControllerHandlerAdapter
调用了Servlet
调用适配器结束
源码地址:
https://gitee.com/xj-louge/pattern.git