1.簡介
學(xué)習(xí)構(gòu)造模式不僅可以提高代碼質(zhì)量,也有助與我們閱讀各類庫的源碼赫粥,因?yàn)閮?yōu)秀的庫中充斥著各種設(shè)計(jì)模式观话。恰巧今天學(xué)習(xí)了建造者模式和責(zé)任鏈模式,于是通過分析OkHttp源碼來鞏固知識(shí)越平。
2.建造者模式
理解:構(gòu)造者中實(shí)現(xiàn)多個(gè)構(gòu)造方法频蛔,可以精細(xì)化構(gòu)造出需要的對象,同時(shí)不必知道構(gòu)造細(xì)節(jié)
建造者模式VS抽象工廠模式
建造者模式:針對某一個(gè)產(chǎn)品進(jìn)行精細(xì)化構(gòu)造秦叛,如定制一個(gè)手機(jī)晦溪。
抽象工廠模式:針對某一系列產(chǎn)品家族,如華為P系列手機(jī)挣跋,每個(gè)工廠只負(fù)責(zé)生產(chǎn)一個(gè)型號(hào)的手機(jī)三圆。
需求:根據(jù)玩家輸入?yún)?shù)生成一個(gè)星球
1)定義星球類
//星球類
class World(val water: String, val land:String, val biological:String){
init {
println("世界生成,水資源:$water, 陸地:$land避咆,物種:$biological")
}
}
2)定義構(gòu)造者接口舟肉,實(shí)現(xiàn)構(gòu)造者類
//構(gòu)造者接口
interface Build{
//構(gòu)建水源
fun buildWater(water: String):Build
//構(gòu)建陸地
fun buildLand(land: String):Build
//構(gòu)建生物
fun buildBiologcial(biological: String):Build
//構(gòu)建世界
fun buildWorld():World
}
//具體Build,即ConcreteBuilder
class WorldBuild : Build{
var water = ""
var land = ""
var biological = ""
override fun buildWater(water: String):Build {
this.water = water
return this
}
override fun buildLand(land: String):Build {
this.land = land
return this
}
override fun buildBiologcial(biological: String):Build {
this.biological = biological
return this
}
override fun buildWorld(): World {
return World(water, land, biological)
}
}
3)調(diào)用
fun main(args:Array<String>){
val builder = WorldBuild()
val world = builder.buildWater("豐富")
.buildLand("稀少")
.buildBiologcial("豐富")
.buildWorld()
}
4)輸出
我們可以看到查库,通過Builder對象內(nèi)部的一系列放法路媚,可以定制一個(gè)符合需求星球。我們甚至可以將Build類作為Product的靜態(tài)內(nèi)部類樊销,借助Build構(gòu)建Product整慎,這個(gè)在最后實(shí)戰(zhàn)時(shí)會(huì)提到脏款。
3.責(zé)任鏈模式
理解:多個(gè)對象形成鏈,請求在上傳遞院领,每個(gè)對象處理后傳個(gè)下個(gè)對象弛矛。最后結(jié)果沿著鏈返回。
以上是個(gè)人理解比然,詳細(xì)可以去查百度
參考博客:https://www.cnblogs.com/ysw-go/p/5432921.html
我們先來定義一個(gè)簡單的需求:
(1)過濾掉句子中的敏感內(nèi)容
(2)替換html標(biāo)簽
分析:我們需要定義過濾器丈氓,然后將過濾器加入List中,然后依次取用對句子進(jìn)行過濾强法。
2)定義請求類和響應(yīng)類
//響應(yīng)類
class Response(var responseStr:String){}
//請求類
class Request(var requestStr:String){}
3)定義過濾器
//過濾器接口
interface Filetr{
fun doFiletr(request: Request, response: Response, chain:FiletrChain): Response
}
//HTML過濾器
class HTMLFilter : Filetr{
override fun doFiletr(request: Request, response: Response, chain: FiletrChain): Response {
//將"<>"換成"[]"
request.requestStr = "HTMLFilter---" + request.requestStr
.replace("<","[")
.replace(">", "]") + "---HTMLFilter"
//通過過濾器鏈調(diào)用下一個(gè)過濾器
return chain.proceed(request, response, chain)
}
}
//敏感詞過濾器
class SenstiveFilter:Filetr{
override fun doFiletr(request: Request, response: Response, chain: FiletrChain): Response {
request.requestStr = "SenstiveFilter---" + request.requestStr
.replace("敏感詞","")
.replace("暴恐", "") + "---SenstiveFilter"
return chain.proceed(request, response, chain)
}
}
4)定義過濾器鏈
class FiletrChain{
//將List封裝一起來万俗,方便操作
private val filters = ArrayList<Filetr>()
private var index = 0
//添加過濾器
fun addFilter(f:Filetr):FiletrChain{
filters.add(f)
return this
}
//用list中的過濾器進(jìn)行過濾
fun proceed(request: Request, response: Response, chain:FiletrChain): Response{
//判斷是否過濾完成
if (index == filters.size){
response.responseStr += request.requestStr
return response
}
//依次調(diào)用下一個(gè)過濾器
val f = filters[index]
index++
return f.doFiletr(request, response, chain)
}
}
5)使用
fun main(args:Array<String>){
val msg = "<Html>,敏感詞饮怯,吃飯,暴恐蓖墅,旅游"
val request = Request(msg)
var respone = Response("response:")
val filerChain = FiletrChain()
respone = filerChain.addFilter(HTMLFilter())
.addFilter(SenstiveFilter())
.proceed(request, respone, filerChain)
println(respone.responseStr)
}
6)輸出
4.實(shí)戰(zhàn):模擬OKHttp攔截器鏈?zhǔn)秸{(diào)用
下面我們通過仿寫OKHttp中的鏈?zhǔn)秸{(diào)用來鞏固一下上面的知識(shí)库倘。
1)首先用建造者模式來寫request類论矾,寫的略微像點(diǎn)樣子教翩,如下:
//請求類
class Request(builder: Builder) {
var requestStr:String
private var url:String? = null
private var method:String? = null
init {
this.requestStr = builder.requestStr
this.url = builder.url
this.method = builder.method
}
//靜態(tài)內(nèi)部類
class Builder{
var requestStr = ""
var url:String? = null
var method:String? = null
init {
this.method = "GET"
}
fun url(url:String):Builder{
this.url = url
return this
}
fun requestStr(requestStr:String):Builder{
this.requestStr = requestStr
return this
}
fun build():Request{
if (url == null) throw IllegalStateException("url == null")
return Request(this)
}
}
}
//調(diào)用
fun main(args:Array<String>){
val request = Request.Builder()
.url("url")
.build()
}
像okHttp一樣,我們要獲取一個(gè)request時(shí)蚂且,只需要通過Builder()方法配猫,鏈?zhǔn)秸{(diào)用來傳入?yún)?shù)章姓,最后通過.build()來建造一個(gè)request對象。建造者模式代碼完成识埋,還是挺簡單的凡伊,下面我們來實(shí)現(xiàn)okhHttp中的責(zé)任鏈。
2)拿到OKHttp中Interceptor和Chain的定義窒舟,直接復(fù)制如下
interface Interceptor{
fun intercept(chain:Chain): Response
interface Chain{
fun request(): Request
fun proceed(request: Request): Response
}
}
3)將整條責(zé)任鏈封裝
//攔截器鏈
class InterceptorChain(val interceptors:List<Interceptor>, var index:Int, val request: Request):Interceptor.Chain{
override fun request(): Request {
return request
}
//1.調(diào)用index位置的攔截器進(jìn)行處理系忙,返回處理的結(jié)果
override fun proceed(request: Request): Response {
//檢查是否有對應(yīng)的攔截器
if (index >= interceptors.size){
throw AssertionError()
}
//獲取當(dāng)前鏈位置對應(yīng)的攔截器
val interceptor = interceptors[index]
//2.獲取下一個(gè)鏈,將攔截器集合傳入惠豺,下標(biāo)+1指向下一個(gè)攔截器
val next = InterceptorChain(interceptors, index+1, request)
//3.當(dāng)前攔截器進(jìn)行攔截處理,將攔截器鏈傳入
val response = interceptor.intercept(next)
//do check for response
//返回index+1位置攔截器處理后的結(jié)果
return response
}
}
主要有兩個(gè)方法:
request():返回一個(gè)請求Request.
proceed():調(diào)用當(dāng)前位置攔截器進(jìn)行攔截银还,并獲取下一個(gè)攔截器
4)定義攔截器
//向服務(wù)器發(fā)送請求的攔截器
class CallServerInterceptor : Interceptor{
override fun intercept(chain: Interceptor.Chain): Response {
//模擬向服務(wù)器發(fā)送請求风宁,獲取返回?cái)?shù)據(jù)
return Response("<Html>,敏感詞蛹疯,吃飯戒财,暴恐,旅游")
}
}
//Html攔截器
class HTMLInterceptor : Interceptor{
override fun intercept(chain: Interceptor.Chain): Response {
val oldRequest = chain.request()
//do something
val newRequest = oldRequest
//4.調(diào)用鏈中下一個(gè)攔截器捺弦,獲取處理后的結(jié)果
val response = chain.proceed(newRequest)
//處理結(jié)果饮寞,返回給上一個(gè)攔截器
response.responseStr = response.responseStr
.replace("<", "[")
.replace(">", "]")
return response
}
}
//敏感詞攔截器
class SenstiveInterceptor : Interceptor{
override fun intercept(chain: Interceptor.Chain): Response {
val response = chain.proceed(chain.request())
response.responseStr = response.responseStr
.replace("敏感詞","")
.replace("暴恐", "")
return response
}
}
這里定義了三個(gè)攔截器,可在調(diào)用下個(gè)攔截器之前對request進(jìn)行處理列吼;或者在下一個(gè)攔截器處理后幽崩,對結(jié)果進(jìn)行處理,這里就對應(yīng)不同的過濾條件寞钥。
5)仿寫一個(gè)call,添加一些默認(rèn)攔截器
//封裝默認(rèn)攔截器
class Call(val originalRequest: Request){
@Throws(IOException::class)
fun getResponseWithInterceptorChain(): Response {
val interceptors = ArrayList<Interceptor>()
//添加攔截器,可以暴露方法慌申,以添加自定義攔截器
interceptors.add(HTMLInterceptor())
interceptors.add(SenstiveInterceptor())
interceptors.add(CallServerInterceptor())
val chain = InterceptorChain(interceptors, 0, originalRequest)
return chain.proceed(originalRequest)
}
}
我們可以在call中,添加一些必備的攔截器理郑,如CallServerInterceptor ,同時(shí)可以暴露方法蹄溉,給用戶添加自定攔截器。
6)整體使用:
fun main(args:Array<String>){
val request = Request.Builder()
.url("url")
.build()
val call = Call(request)
val response = call.getResponseWithInterceptorChain()
println(response.responseStr)
}
先通過建造者模式獲取request您炉,然后實(shí)例化call對象类缤,調(diào)用getResponseWithInterceptorChain(),使得request沿著攔截器鏈往下傳遞邻吭,最后到達(dá)CallServerInterceptor 發(fā)起網(wǎng)絡(luò)請求。response 再沿著鏈返回宴霸,每個(gè)攔截器對response進(jìn)行處理囱晴。