适配器模式
适配器模式
基本介绍
- 适配器模式将某个类的接口转换成客户端期望的另一个接口表示,主要的目的是:让原本因接口不匹配不能一起工作的两个类可以协同工作。其别名为包装器(Wrapper)
- 适配器模式属于结构型模式
- 主要分为三类:类适配器模式、对象适配器模式、接口适配器模式
工作原理
- 适配器模式:将一个类的接口转换成另一种接口,让原本接口不兼容的类可以兼容。
- 从用户的角度看不到被适配者,是解耦的。
- 用户调用适配器转化出来的目标接口方法,适配器再调用被适配者的相关接口方法
- 用户收到反馈结果,感觉只是和目标接口交互。
类适配器模式
类适配器模式介绍
Adapter类,
通过集成src类,实现dst接口,
完成src——>的适配
类适配器模式类图实例
类适配器模式代码实例
Voltage220V 类
public class Voltage220V {
int src = 220;
public int output220V() {
System.out.println("电压=" + src + "伏");
return src;
}
}
Voltage5V 接口
public interface Voltage5V {
public int output5V();
}
VoltageAdapter类作为适配器
public class VoltageAdapter extends Voltage220V implements Voltage5V {
@Override
public int output5V() {
int src = output220V();
int dstV = src / 44;
return dstV;
}
}
Phone 具体的实现
public class Phone {
public void charging(Voltage5V voltage5V){
if (voltage5V.output5V()==5){
System.out.println("电压为5V,可以充电~~~");
}else if (voltage5V.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());
}
}
类适配器模式注意事项和细节
- Java是单继承机制,所以类适配器需要继承src类这一点算是一个缺点,因为这要求dst必须是接口,有一定局限性;
- src类的方法在Adapter中都会暴露出来,也增加了使用的成本。
- 由于其继承了src类,所以它可以根据需求重写src类的方法,使得Adapter的灵活性增强了。
对象适配器模式
对象适配器模式介绍
- 基本思路和类的适配器模式相同,只是将Adapter类作修改,不是继承src类,而是持有src类的实例,以解决兼容性的问题。即:持有src类,实现dst类接口,完成src——>dst的适配
- 根据“合成复用原则”,在系统中尽量使用关联关系来替代继承关系。
- 对象适配器模式是适配器模式常用的一种。
对象适配器模式类图实例
对象适配器模式代码实例
Voltage220V类
public class Voltage220V {
int src = 220;
public int output220V() {
System.out.println("电压=" + src + "伏");
return src;
}
}
Voltage5V 接口
public interface Voltage5V {
public int output5V();
}
VoltageAdapter 发生了变化,不再继承Voltage220V类,而是采用聚合的方式,降低了两个类之间的耦合关系,减小了类之间的入侵,符合开闭原则和合成复用原则。
public class VoltageAdapter implements Voltage5V {
private Voltage220V voltage220V = null;
public VoltageAdapter(Voltage220V voltage220V) {
this.voltage220V = voltage220V;
}
@Override
public int output5V() {
int dst = 0;
if (null != voltage220V) {
int src = voltage220V.output220V();
System.out.println("使用对象适配器,进行适配~~");
dst = src/44;
System.out.println("适配完成,输出的电压为="+dst);
}
return dst;
}
}
Phone 类
public class Phone {
public void charging(Voltage5V voltage5V){
if (voltage5V.output5V()==5){
System.out.println("电压为5V,可以充电~~~");
}else if (voltage5V.output5V()>5){
System.out.println("电压大于5V,不能充电~~");
}
}
}
Client测试用例中新增了一个new Voltage220V(),是因为在初始化VoltageAdapter类时,其触发了含参构造器。
public class Client {
public static void main(String[] args) {
System.out.println("=== 类适配器模式 ===");
Phone phone = new Phone();
phone.charging(new VoltageAdapter(new Voltage220V()));
}
}
对象适配器模式注意事项和细节
- 对象适配器和类适配器其实算是同一种思想,只不过实现方式不同。根据合成复用原则,使用组合替代继承,所以它解决了类适配器必须继承src的局限性可能,也不再要求dst必须是接口。
- 使用成本更低,更灵活。(ps:成本的意思是侵入性更小,因为尽量使用聚合会比继承更加能够实现类之间的解耦合)
接口适配器模式
接口适配器模式介绍
- 一些书籍又称为:适配器模式或缺省适配器模式。
- 当不需要全部实现接口提供的方法时,可先设计一个抽象类实现接口,并为该接口中每个方法提供一个默认实现(空方法),那么该抽象类的子类可有选择地覆盖父类的某些方法来实现需求。
- 适用于一个接口不想使用其所有的方法的情况。
接口适配器模式类图实例
接口适配器模式代码实例
Interface4接口
public interface Interface4 {
public void m1();
public void m2();
public void m3();
public void m4();
}
AbsAdapter抽象类对Interface4空实现。
public abstract class AbsAdapter implements Interface4 {
@Override
public void m1() { }
@Override
public void m2() { }
@Override
public void m3() { }
@Override
public void m4() {}
}
Client 类使用匿名内部类来选择实现接口中的方法。
public class Client {
public static void main(String[] args) {
AbsAdapter absAdapter = new AbsAdapter(){
@Override
public void m1(){
System.out.println("使用了m1的方法");
}
};
}
}
适配器模式在SpringMVC框架应用的源码分析
- SpringMvc中的HandlerAdapter,就使用了适配器模式。
- SpringMVC处理请求的流程
- 使用HandlerAdapter的原因分析;
Spring MVC的工作流程
适配器模式源码分析
DispatcherServlet类中的doDispatch()方法,
根据request请求得到一个Handler,这个Handler就是一个控制器。(参考下图1)
通过不同的Handler来调用相应的方法获得其所属的HandlerAdapter适配器。(参考下图2)
/**
* Process the actual dispatching to the handler.
* <p>The handler will be obtained by applying the servlet's HandlerMappings in order.
* The HandlerAdapter will be obtained by querying the servlet's installed HandlerAdapters
* to find the first that supports the handler class.
* <p>All HTTP methods are handled by this method. It's up to HandlerAdapters or handlers
* themselves to decide which methods are acceptable.
* @param request current HTTP request
* @param response current HTTP response
* @throws Exception in case of any kind of processing failure
*/
protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
HttpServletRequest processedRequest = request;
HandlerExecutionChain mappedHandler = null;
boolean multipartRequestParsed = false;
WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
try {
ModelAndView mv = null;
Exception dispatchException = null;
try {
processedRequest = checkMultipart(request);
multipartRequestParsed = (processedRequest != request);
// Determine handler for the current request.
mappedHandler = getHandler(processedRequest);
if (mappedHandler == null) {
noHandlerFound(processedRequest, response);
return;
}
// Determine handler adapter for the current request.
HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler());
// Process last-modified header, if supported by the handler.
String method = request.getMethod();
boolean isGet = "GET".equals(method);
if (isGet || "HEAD".equals(method)) {
long lastModified = ha.getLastModified(request, mappedHandler.getHandler());
if (new ServletWebRequest(request, response).checkNotModified(lastModified) && isGet) {
return;
}
}
if (!mappedHandler.applyPreHandle(processedRequest, response)) {
return;
}
// Actually invoke the handler.
mv = ha.handle(processedRequest, response, mappedHandler.getHandler());
if (asyncManager.isConcurrentHandlingStarted()) {
return;
}
applyDefaultViewName(processedRequest, mv);
mappedHandler.applyPostHandle(processedRequest, response, mv);
}
catch (Exception ex) {
dispatchException = ex;
}
catch (Throwable err) {
// As of 4.3, we're processing Errors thrown from handler methods as well,
// making them available for @ExceptionHandler methods and other scenarios.
dispatchException = new NestedServletException("Handler dispatch failed", err);
}
processDispatchResult(processedRequest, response, mappedHandler, mv, dispatchException);
}
catch (Exception ex) {
triggerAfterCompletion(processedRequest, response, mappedHandler, ex);
}
catch (Throwable err) {
triggerAfterCompletion(processedRequest, response, mappedHandler,
new NestedServletException("Handler processing failed", err));
}
finally {
if (asyncManager.isConcurrentHandlingStarted()) {
// Instead of postHandle and afterCompletion
if (mappedHandler != null) {
mappedHandler.applyAfterConcurrentHandlingStarted(processedRequest, response);
}
}
else {
// Clean up any resources used by a multipart request.
if (multipartRequestParsed) {
cleanupMultipart(processedRequest);
}
}
}
}
追踪getHandlerAdapter()方法,其返回的是一个HandlerAdapter 接口
通过for循环来遍历所有的handlerAdapters,比对传过来的Object handler返回请求对应的HandlerAdapter.
/**
* Return the HandlerAdapter for this handler object.
* @param handler the handler object to find an adapter for
* @throws ServletException if no HandlerAdapter can be found for the handler. This is a fatal error.
*/
protected HandlerAdapter getHandlerAdapter(Object handler) throws ServletException {
if (this.handlerAdapters != null) {
for (HandlerAdapter adapter : this.handlerAdapters) {
if (adapter.supports(handler)) {
return adapter;
}
}
}
throw new ServletException("No adapter for handler [" + handler +
"]: The DispatcherServlet configuration needs to include a HandlerAdapter that supports this handler");
}
追踪HandlerAdapter 接口,查看它具体的实现类有哪些.以下就是HandlerAdapter 接口的具体实现类
AbstractHandlerMethodAdapter
SimpleServletHandlerAdapter
HandlerFunctionAdapter
HttpRequestHandlerAdapter
SimpleControllerHandlerAdapter
DispatchServlet类图实例
适配器模式的注意事项和细节
- 三种命名方式,根据src是以怎样的形式给到Adapter(在Adapter里的形式)来命名的。
- 三种传递方式
- 类适配器:以类传递,在Adapter里,就是将src当做类,继承的方式。
- 对象适配器: 以对象的方式,在Adapter里,将src作为一个对象,可以通过构造器或者setter方法的方式传入并持有。
- 接口适配器:以接口的方式,在Adapter里,将src作为一个接口,由其子类选择进行实现。
- Adapter模式最大的作用还是将原本不兼容的接口融合在一起工作。
- 实际开发中,实现起来不拘泥于所讲解的三种经典方式。