1)适配器模式是将某个类的接口转换成客户端期望的另一个接口表示,主要目的是兼容性,让原本因接口不匹配不能一起工作的2个类能协同工作。
2)适配器模式属于结构模式
3)适配器分为:类适配器,对象适配器,接口适配器
类适配器模式 实现一个简单业务,给手机充电需要充电线,充电线就是把220v交流电转换成5v直流电给手机充电,因为手机无法直接接入220v电压,下面为UML类图
对象适配器模式UML类图
接口适配器模式 用SpringMVC中的Handler来写个简易版的
crontroller 类和实现它的子类
public interface Controller {
}
class SimpleController implements Controller{
public void doSimple() {
System.out.println("Simple...");
}
}
class HttpController implements Controller{
public void doHttp() {
System.out.print("Http...");
}
}
class AnnotationController implements Controller{
public void doAnnotation(){
System.out.println("Annotation...");
}
}
Handler类和实现它的子类
public interface HandlerAdapter {
public boolean support(Object handler);
public void handle(Object handler);
}
class SimpleHanderAdapter implements HandlerAdapter{
@Override
public boolean support(Object handler) {
return handler instanceof SimpleController;
}
@Override
public void handle(Object handler) {
((SimpleController)handler).doSimple();
}
}
class HttpHanderAdapter implements HandlerAdapter{
@Override
public boolean support(Object handler) {
return handler instanceof HttpController;
}
@Override
public void handle(Object handler) {
((HttpController)handler).doHttp();
}
}
class AnnotationHanderAdapter implements HandlerAdapter{
@Override
public boolean support(Object handler) {
return handler instanceof AnnotationController;
}
@Override
public void handle(Object handler) {
((AnnotationController)handler).doAnnotation();
}
}
DispatchServlet类
public class DispatcherServlet {
public static List<HandlerAdapter> list = new ArrayList<>();
public DispatcherServlet() {
list.add(new SimpleHanderAdapter());
list.add(new HttpHanderAdapter());
list.add(new AnnotationHanderAdapter());
}
public void doDispatch() {
//获取一个controller
Controller controller = new HttpController();
//得到一个适配器
HandlerAdapter adapter = getAdapter(controller);
//执行
adapter.handle(controller);
}
public HandlerAdapter getAdapter(Controller controller) {
for (HandlerAdapter handlerAdapter : list) {
if(handlerAdapter.support(controller)) {
return handlerAdapter;
}
}
return null;
}
//主程序入口
public static void main(String[] args) {
new DispatcherServlet().doDispatch();
}
}