本著針對面試屈糊,不負責任的態(tài)度玩徊,寫下《面試總結》系列租悄。本系列記錄面試過程中各個知識點,而不是入門系列恩袱,如果有不懂的自行學習泣棋。
轉(zhuǎn)載請標明出處,本文地址:http://www.reibang.com/p/491603d9fadc
涉及到的設計模式
外觀模式,構建者模式畔塔,工廠模式潭辈,代理模式,適配器模式澈吨,策略模式把敢,觀察者模式
概括
Retrofit就是一個網(wǎng)絡請求框架的封裝,底層的網(wǎng)絡請求默認使用的Okhttp谅辣,本身只是簡化了用戶網(wǎng)絡請求的參數(shù)配置等修赞,還能與Rxjava相結合,使用起來更加簡潔方便桑阶。
- App應用程序通過Retrofit請求網(wǎng)絡柏副,實際上是使用Retrofit接口層封裝請求參數(shù),之后由OkHttp完成后續(xù)的請求操作蚣录。
- 在服務端返回數(shù)據(jù)之后割择,OkHttp將原始的結果交給Retrofit,Retrofit根據(jù)用戶的需求對結果進行解析包归。
- 完成數(shù)據(jù)的轉(zhuǎn)化(converterFactory),適配(callAdapterFactory),通過設計模式進行各種擴展公壤。
使用
@GET("/user/{user}/repos")
Call<List<Repo>> listRepos(@Path("user") String user);
//call封裝了整個okhttp的請求
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.github.com/")
.addConverterFactory(GsonConverteractory.create())
//.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
//converterFactory
//后續(xù)交給okhttp
使用Retrofit的七步驟
- 添加Retrofit依賴换可,網(wǎng)絡權限
- 定義接收服務器返回數(shù)據(jù)的Bean
- 創(chuàng)建網(wǎng)絡請求的接口,使用注解(動態(tài)代理厦幅,核心)
- builder模式創(chuàng)建Retrofit實例沾鳄,converter,calladapter...
- 創(chuàng)建接口實例确憨,調(diào)用具體的網(wǎng)絡請求
- call同步/異步網(wǎng)絡請求
- 處理服務器返回的數(shù)據(jù)
Retrofit網(wǎng)絡通信八步驟
- 創(chuàng)建Retrofit實例
- 定義網(wǎng)絡請求接口译荞,并為接口中的方法添加注解
- 通過動態(tài)代理生成網(wǎng)絡請求對象
- 通過網(wǎng)絡請求適配器將網(wǎng)絡請求對象進行平臺適配
- 通過網(wǎng)絡請求執(zhí)行器,發(fā)送網(wǎng)絡請求(call)
- 通過數(shù)據(jù)解析器解析數(shù)據(jù)
- 通過回調(diào)執(zhí)行器休弃,切換線程
- 用戶在主線程處理返回結果
代理
為其他對象提供一種代理吞歼,用以控制對這個對象的訪問
靜態(tài)
-
動態(tài)
- 在程序運行時創(chuàng)建的代理方式
- 無侵入增強
- jdk動態(tài)代理 vs cglib
jdk動態(tài)代理
- 只能為接口動態(tài)
- InvocationHandler必須要實現(xiàn)
- invoke的參數(shù)中獲取參數(shù)
- invoke的返回值返回給使用者
- newProxyInstance中傳入InvocationHandler
總結:
- 運行期
- InvocationHandler接口和Proxy類
- 動態(tài)代理與靜態(tài)代理的不同
源碼
- serviceMethonCache //緩存,網(wǎng)絡請求對象
- Factory callFactory //默認ok
- HttpUrl baseUrl
- List<Converter.Factory> converterFactories
- List<CallAdapter.Factory> callAdapterFactories
- Executor callbackExecutor //執(zhí)行回調(diào)
- boolean validateEagerly //是否立即解析接口中方法
builder
- platform
單例獲取不同平臺
Android平臺中MainthreadExecutor
callAdapterFactory
通過calladapter將原始Call進行封裝塔猾,找到對應的執(zhí)行器篙骡。如rxjavaCallFactory對應的Observable,轉(zhuǎn)換形式Call<T> --> Observable<T>
converterFactory
數(shù)據(jù)解析Converter丈甸,將response通過converterFactory轉(zhuǎn)換成對應的數(shù)據(jù)形式糯俗,GsonConverterFactory,F(xiàn)astJsonConverterFactory睦擂。
Retrofit
Retrofit核心類得湘,對外提供接口。通過retrofit.create()創(chuàng)建retrofit實例顿仇,外觀模式淘正。在create()方法中,使用動態(tài)代理模式對請求的接口中方法進行封裝(ServiceMethod)夺欲,初始化OkhttpCall跪帝。
ServiceMethod
核心處理類,解析方法和注解些阅,toRequest()方法中生成HttpRequest伞剑。創(chuàng)建responseConverter(將response流轉(zhuǎn)換為String或?qū)嶓w),創(chuàng)建callAdapter
OkhttpCall
是對okhttp3.Call的封裝調(diào)用