泰国插座用的是两孔的(欧标),可以买个多功能转换插头(适配器),这样就可以使用了。
适配器模式(Adapter Pattern)将某个类的接口转换成客户端期望的另一个接口表示,主的目的是兼容性,让原本因接口不匹配不能一起工作的两个类可以协同工作。其别名为包装器(Wrapper)
适配器模式属于结构型模式
主要分为三类:类适配器模式、对象适配器模式、接口适配器模式
适配器模式:将一个类的接口转换成另一种接口。让原本接口不兼容的类可以兼容
从用户的角度看不到被适配者,是解耦的
用户调用适配器转化出来的目标接口方法,适配器再调用被适配者的相关接口方法
用户收到反馈结果,感觉只是和目标接口交互,如图
基本介绍:Adapter 类,通过继承 src 类,实现 dst 类接口,完成 src->dst 的适配。
思路分析(类图)
代码实现
package com.atguigu.adapter.classadapter;
/**
* @author Lenovo
*
*/
public class Client {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("类适配器模式");
Phone phone = new Phone();
phone.charging(new VoltageAdapter());
}
}
package com.atguigu.adapter.classadapter;
/**
* 适配接口
*
* @author Lenovo
*
*/
public interface IVoltage5V {
/**
* 输出5V
*
* @return
*/
public int output5V();
}
package com.atguigu.adapter.classadapter;
/**
* @author Lenovo
*
*/
public class Phone {
public void charging(IVoltage5V iVoltage5V) {
if (iVoltage5V.output5V() == 5) {
System.out.println("电压为5V,可以充电~~");
} else if (iVoltage5V.output5V() > 5) {
System.out.println("电压大于5V,不能充电~~");
}
}
}
package com.atguigu.adapter.classadapter;
/**
* 被适配的类
*
* @author Lenovo
*
*/
public class Voltage220V {
/**
* 输出220V电压
*
* @return
*/
public int output220V() {
int src = 220;
System.out.println("电压=" + src + "伏");
return src;
}
}
package com.atguigu.adapter.classadapter;
/**
* 适配器类
*
* @author Lenovo
*
*/
public class VoltageAdapter extends Voltage220V implements IVoltage5V {
@Override
public int output5V() {
// TODO Auto-generated method stub
// 获取到220v电压
int srcV = super.output220V();
// 转成5V
int dstV = srcV / 44;
return dstV;
}
}
Java 是单继承机制,所以类适配器需要继承 src 类这一点算是一个缺点, 因为这要求 dst 必须是接口,有一定局限性;
src 类的方法在 Adapter 中都会暴露出来,也增加了使用的成本。
由于其继承了 src 类,所以它可以根据需求重写 src 类的方法,使得 Adapter 的灵活性增强了。
基本思路和类的适配器模式相同,只是将 Adapter 类作修改,不是继承 src 类,而是持有 src 类的实例,以解决兼容性的问题。 即:持有 src 类,实现 dst 类接口,完成 src->dst 的适配
根据“合成复用原则”,在系统中尽量使用关联关系(聚合)来替代继承关系。
对象适配器模式是适配器模式常用的一种
应用实例说明
以生活中充电器的例子来讲解适配器,充电器本身相当于 Adapter,220V 交流电相当于 src(即被适配者),我们的目 dst(即目标)是 5V 直流电,使用对象适配器模式完成。
思路分析(类图)
只需修改适配器即可, 如下:
package com.atguigu.adapter.objectadapter;
/**
* @author Lenovo
*
*/
public class Client {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("类适配器模式");
Phone phone = new Phone();
phone.charging(new VoltageAdapter(new Voltage220V()));
}
}
package com.atguigu.adapter.objectadapter;
/**
* 适配器类
*
* @author Lenovo
*
*/
public class VoltageAdapter implements IVoltage5V {
/**
* 关联关系-聚合
*/
private Voltage220V voltage220V;
/**
* 通过构造器,传入一个 Voltage220V 实例
*
* @param voltage220v
*/
public VoltageAdapter(Voltage220V voltage220v) {
this.voltage220V = voltage220v;
}
@Override
public int output5V() {
// TODO Auto-generated method stub
int dst = 0;
if (null != voltage220V) {
// 获取 220V 电压
int src = voltage220V.output220V();
System.out.println("使用对象适配器,进行适配~~");
dst = src / 44;
System.out.println("适配完成,输出的电压为=" + dst);
}
return dst;
}
}
对象适配器和类适配器其实算是同一种思想,只不过实现方式不同。根据合成复用原则,使用组合替代继承, 所以它解决了类适配器必须继承 src 的局限性问题,也不再要求 dst必须是接口。
使用成本更低,更灵活。
一些书籍称为:适配器模式(Default Adapter Pattern)或缺省适配器模式。
核心思路:当不需要全部实现接口提供的方法时,可先设计一个抽象类实现接口,并为该接口中每个方法提供一个默认实现(空方法),那么该抽象类的子类可有选择地覆盖父类的某些方法来实现需求
适用于一个接口不想使用其所有的方法的情况。
Android 中的属性动画 ValueAnimator 类可以通过addListener(AnimatorListener listener)
方法添加监听器, 那么常规写法如右
ValueAnimator valueAnimator = ValueAnimator.oflnt(0,100);
valueAnimator.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation){
}
@Override
public void onAnimationEnd(Animator animation){
}
@Override
public void onAnimationCancel(Animator animation){
}
@Override
public void onAnimationRepeat(Animator animation){
}
});
valueAnimator.start();
有时候我们不想实现 Animator.AnimatorListener 接口的全部方法,我们只想监听 onAnimationStart,我们会如下写
ValueAnimator valueAnimator=ValueAnimator.oflnt(0,100);
valueAnimator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationStart(Animator animation){
// xxxx具体实现
}
});
valueAnimator.start();
AnimatorListenerAdapter 类,就是一个接口适配器,代码如右图:它空实现了Animator.AnimatorListener 类(src)的所有方法
public static interface AnimatorListener {
void onAnimationStart(Animator animation);
void onAnimationEnd(Animator animation);
void onAnimationCancel(Animator animation):
void onAnimationRepeat(Animator animation);
}
public abstract class AnimatorListenerAdapter implements Animator.AnimatorListener {
@Override
public void onAnimationCancel(Animator animation) {
// 默认实现
}
@Override
public void onAnimationEnd(Animator animation) {
}
@Override
public void onAnimationRepeat(Animator animation) {
}
@Override
public void onAnimationStart(Animator animation) {
}
@Override
public void onAnimationPause(Animator animation) {
}
@Override
public void onAnimationResume(Animator animation) {
}
}
程序里的匿名内部类就是 Listener 具体实现类
new AnimatorListenerAdapter() {
@Override
public void onAnimationStart(Animator animation) {
// xxxx具体实现
}
}
案例说明
package com.atguigu.adapter.interfaceadapter;
/**
* @author Lenovo
*
*/
public interface Interface4 {
public void m1();
public void m2();
public void m3();
public void m4();
}
package com.atguigu.adapter.interfaceadapter;
/**
* @author Lenovo
*
*/
public class AbsAdapter implements Interface4 {
@Override
public void m1() {
// TODO Auto-generated method stub
}
@Override
public void m2() {
// TODO Auto-generated method stub
}
@Override
public void m3() {
// TODO Auto-generated method stub
}
@Override
public void m4() {
// TODO Auto-generated method stub
}
}
package com.atguigu.adapter.interfaceadapter;
/**
* @author Lenovo
*
*/
public class Client {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
// 只需要去覆盖我们需要使用接口方法
AbsAdapter absAdapter = new AbsAdapter() {
@Override
public void m1() {
// TODO Auto-generated method stub
System.out.println("使用了m1的方法");
}
};
absAdapter.m1();
}
}
SpringMvc 中的 HandlerAdapter, 就使用了适配器模式
SpringMVC 处理请求的流程回顾
使用 HandlerAdapter 的原因分析:
可以看到处理器的类型不同,有多重实现方式,那么调用方式就不是确定的,如果需要直接调用 Controller 方法,需要调用的时候就得不断是使用 if else 来进行判断是哪一种子类然后执行。那么如果后面要扩展 Controller, 就得修改原来的代码,这样违背了 OCP 原则。
代码分析+Debug 源码
DispatcherServlet:
mappedHandler = getHandler(processedRequest); ==> 获取控制器
HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler()); ==> 获取适配器
mv = ha.handle(processedRequest, response, mappedHandler.getHandler()); ==> 通过获取的适配器调用handle方法
/**
* 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);
}
}
}
}
返回一个HandlerAdapter
遍历Adapter,返回支持的适配器
/**
* 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 的实现子类有多种,使得每一种Controller有一种对应的适配器实现类,每种Controller有不同的实现方式
动手写 SpringMVC 通过适配器设计模式获取到对应的 Controller 的源码
package com.atguigu.springmvc;
/**
* @author Lenovo
*
*/
public interface Controller {
}
class HttpController implements Controller {
public void doHttpHandler() {
System.out.println("http...");
}
}
class SimpleController implements Controller {
public void doSimpleHandler() {
System.out.println("simple...");
}
}
class AnnotationController implements Controller {
public void doAnnotationHandler() {
System.out.println("annotation...");
}
}
package com.atguigu.springmvc;
import java.util.ArrayList;
import java.util.List;
/**
* @author Lenovo
*
*/
public class DispatchServlet {
public static List<HandlerAdapter> handlerAdapters = new ArrayList<>();
public static void main(String[] args) {
new DispatchServlet().doDispatch();
}
/**
*
*/
public DispatchServlet() {
// TODO Auto-generated constructor stub
handlerAdapters.add(new AnnotationHandlerAdapter());
handlerAdapters.add(new HttpHandlerAdapter());
handlerAdapters.add(new SimpleHandlerAdapter());
}
public void doDispatch() {
// 此处模拟SpringMVC从request取handler的对象,
// 适配器可以获取到希望的Controller
// HttpController controller=new HttpController();
AnnotationController controller = new AnnotationController();
// StapleController controller=new SimpleController();
// 得到对应适配器
HandlerAdapter adapter = getHandler(controller);
// 通过适配器执行对应的controller对应方法
adapter.handle(controller);
}
public HandlerAdapter getHandler(Controller controller) {
for (HandlerAdapter adapter : this.handlerAdapters) {
if (adapter.supports(controller)) {
return adapter;
}
}
return null;
}
}
package com.atguigu.springmvc;
/**
* 定义一个Adapter接口
*
* @author Lenovo
*
*/
public interface HandlerAdapter {
public boolean supports(Object handler);
public void handle(Object handler);
}
/**
* 多种适配器类
*
* @author Lenovo
*
*/
class SimpleHandlerAdapter implements HandlerAdapter {
@Override
public boolean supports(Object handler) {
// TODO Auto-generated method stub
return (handler instanceof SimpleController);
}
@Override
public void handle(Object handler) {
// TODO Auto-generated method stub
((SimpleController) handler).doSimpleHandler();
}
}
class HttpHandlerAdapter implements HandlerAdapter {
@Override
public boolean supports(Object handler) {
// TODO Auto-generated method stub
return (handler instanceof HttpController);
}
@Override
public void handle(Object handler) {
// TODO Auto-generated method stub
((HttpController) handler).doHttpHandler();
}
}
class AnnotationHandlerAdapter implements HandlerAdapter {
@Override
public boolean supports(Object handler) {
// TODO Auto-generated method stub
return (handler instanceof AnnotationController);
}
@Override
public void handle(Object handler) {
// TODO Auto-generated method stub
((AnnotationController) handler).doAnnotationHandler();
}
}
说明
三种命名方式,是根据 src 是以怎样的形式给到 Adapter(在 Adapter 里的形式)来命名的。
Adapter 模式最大的作用还是将原本不兼容的接口融合在一起工作。
实际开发中,实现起来不拘泥于我们讲解的三种经典形式
原文:https://www.cnblogs.com/iamfatotaku/p/14604106.html