设计模式之适配器模式
# 设计模式之适配器模式
# 一、简介
将一种接口转换成另一种接口,同时不改变其功能的正常性
例如:美国电器 110V,中国 220V,就要有一个适配器将 110V 转化为 220V
# 二、实现方式
# 1、类适配器模式
通过继承的方式来实现,不建议,此处不做详细描述
# 2、对象适配器模式
通过组合的方式来实现,建议使用

Adapter类:
public class Adapter implements CN220V {
private US110V us110V;
public Adapter(US110V us110V) {
this.us110V = us110V;
}
public int output220v() {
return us110V.output110v() * 2;
}
}
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
CN220V类:
public interface CN220V {
/**
* 输出220V电压
* @return
*/
int output220v();
}
1
2
3
4
5
6
7
2
3
4
5
6
7
US110V类:
public class US110V {
/**
* 输出110V电压
* @return
*/
public int output110v(){
return 110;
}
}
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
# 三、应用场景
# 1、SpringCloud Gateway中的适配器模式和责任链模式:GlobalFilter、GatewayFilter和DefaultGatewayFilterChain
在SpringCloud Gateway中,有两个接口GlobalFilter、GatewayFilter,都是用来拦截处理请求的
public interface GatewayFilter extends ShortcutConfigurable {
String NAME_KEY = "name";
String VALUE_KEY = "value";
Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain);
}
1
2
3
4
5
6
2
3
4
5
6
我们会通过执行链DefaultGatewayFilterChain,将过滤器串联起来进行链式调用,所有的过滤器都存放在filters 数组中,并维护一个索引index来记录当前遍历到哪一个filter

这时候使用了GatewayFilterAdapter将GlobalFilter的接口转换成GatewayFilter接口

# 2、SpringMVC中HandlerAdapter的使用
在SpringMVC中,有四种Handler,不同的Handler由不同的HandlerAdapter处理,其方法如下:

以RequestMappingHandlerAdapter为例,它实现了HandlerAdapter,重写了handle方法,传入一个Object类型的hander对象,随后进行转换,处理业务逻辑,此处可以认为是对象适配器模式的一个变种

# 四、思维导图
