序言:
在软件工程中,一个好的软件作品不仅表现在功能齐全、界面美观、操作简单易上手等方面,还在于软件的实现方式、代码结构、功能扩展和后期维护。优秀的软件就好比结实耐用又好看的房子,地基扎实,框架结构坚固同时预留有足够合理的门、窗、水、电以及后期的加层装修等位置;优秀的软件界面美观、操作简单,功能齐全,同时预留有足够的可配置性,可扩展性,可维护性等等功能。
相信从事Android开发的大神们应该都知道Android中的一个非常优秀的轻量级网络请求框架–okhttp,它是由美国移动支付Square公司贡献(该公司还贡献了Picasso、Retrofit、OkIO、leakcanary)。为什么么介绍okhttp呢,因为Okhttp简单、高效、高可扩展可维护性、代码结构清晰、方便阅读理解。本人也是okhttp的学习使用者之一,因觉得它的代码结构清晰易阅读,特别是它里面使用的一个模式令我甚感兴趣,简单而又藏有难度,同时却恰到好处的实现了软件的功能。个人认为这是一个非常好用的模式,因此特意想记下以便后边仿照使用。
模式命名为:拦截器模式。此模式有四个对象,分别为:请求、响应、拦截器、链条。实现的功能就是通过拦截器拦截链条中的请求响应,以此达到类似监听、中途修改的目的。下面以软件使用的一个非常普遍的场景为例来解释拦截器模式的使用–网络请求。
1,网络请求
/**
* 请求
* Created by huanghp on 2018/10/29.
* Email h1132760021@sina.com
*/
public class Request {
}
2,网络响应
/**
* 网络响应
* Created by huanghp on 2018/10/29.
* Email h1132760021@sina.com
*/
public class Response {
}
3,拦截器接口
/**
* 拦截器接口
* Created by huanghp on 2018/10/29.
* Email h1132760021@sina.com
*/
public interface Interceptor {
Response intercept(Chain chain);
/**
* 拦截链条
*/
interface Chain {
Request request();
Response process(Request request);
}
}
4,具体拦截器
/**
* 具体拦截器
* Created by huanghp on 2018/10/29.
* Email h1132760021@sina.com
*/
public class ConcreteInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) {
//此处可以监听打印chain.request()的参数等信息
Response response = chain.process(chain.request());
//此处可以监听打印Response的参数等信息
return response;
}
}
通过添加具体的拦截器,能够拦截到链条中的所有请求和响应,以此达到监听或中途修改请求或响应的目的
/**
* fileDesc
* Created by huanghp on 2018/10/29.
* Email h1132760021@sina.com
*/
public class Test {
static List<Interceptor> interceptors = new ArrayList<>();
public static void main() {
Interceptor interceptor1 = new ConcreteInterceptor();
Interceptor interceptor2 = new ConcreteInterceptor();
Interceptor interceptor3 = new ConcreteInterceptor();
interceptors.add(interceptor1);
interceptors.add(interceptor2);
interceptors.add(interceptor3);
Request request = new Request();
Interceptor.Chain chain = new AppChain(0, request);
chain.process(request);
}
static class AppChain implements Interceptor.Chain {
int index;
Request request;
public AppChain(int index, Request request) {
this.index = index;
this.request = request;
}
@Override
public Request request() {
return request;
}
@Override
public Response process(Request request) {
if (index < interceptors.size()) {
Interceptor.Chain chain = new AppChain(index + 1, request);
Interceptor interceptor = interceptors.get(index);
Response interceptedResponse = interceptor.intercept(chain);
if (interceptedResponse == null) {
throw new NullPointerException("application interceptor " + interceptor
+ " returned null");
}
return interceptedResponse;
}
//No more interceptors. Do finally.
return getResponse();
}
/**
* 如果没一个拦截器返回了Response,此方法返回最终Response
*
* @return
*/
@Notnull
private Response getResponse() {
return new Response();
}
}
}
拦截器模式:简单的4个角色,代码简单高效,就达到了拦截请求与响应的功能。可谓精、简!
ok,本次的拦截器模式讲解到此结束。