Kotlin enum (實(shí)現(xiàn)網(wǎng)絡(luò)加載架構(gòu))
- interface
interface NetManager {
enum class ForBind(var type:String,var url:Any){
GET("",""),
POST("",""),
DELETE("",""),
UPDATE("","")
}
fun get(url: Any)
fun post(url: Any)
fun delete(url: Any)
fun update(url: Any)
fun loadBind(bind: NetManager.ForBind)
}
- ConcreteNetManager (private 靈魂很重要)
private enum class ConcreteNetManager:NetManager {
Notify {
override fun loadBind(bind: NetManager.ForBind) {
bind.let {
when (it) {
NetManager.ForBind.GET -> {
when (it.type) {
"get 01" -> get(it.url)
"get 02" -> get(it.url)
"get 03" -> get(it.url)
}
}
NetManager.ForBind.POST -> {
when (it.type) {
"post 01" -> post(it.url)
"post 02" -> post(it.url)
"post 03" -> post(it.url)
}
}
NetManager.ForBind.DELETE -> {
when (it.type) {
"delete 01" -> delete(it.url)
"delete 02" -> delete(it.url)
"delete 03" -> delete(it.url)
}
}
NetManager.ForBind.UPDATE -> {
when (it.type) {
"update 01" -> update(it.url)
"update 02" -> update(it.url)
"update 03" -> update(it.url)
}
}
}
}
}
override fun get(url: Any) {
TODO("Not yet implemented")
}
override fun post(url: Any) {
TODO("Not yet implemented")
}
override fun delete(url: Any) {
TODO("Not yet implemented")
}
override fun update(url: Any) {
TODO("Not yet implemented")
}
}
}
- 3.ClientForNetMnager
// 客戶端使用
class ClientForNetMnager {
companion object {
fun Get(type: String,url: Any){
val any = NetManager.ForBind.GET.let {
it.type = type
it.url = url
ConcreteNetManager.Notify.loadBind(it)
}
}
fun Post(type: String,url: Any){
val any = NetManager.ForBind.POST.let {
it.type = type
it.url = url
ConcreteNetManager.Notify.loadBind(it)
}
}
fun Delete(type: String,url: Any){
val any = NetManager.ForBind.DELETE.let {
it.type = type
it.url = url
ConcreteNetManager.Notify.loadBind(it)
}
}
fun Update(type: String,url: Any){
val any = NetManager.ForBind.UPDATE.let {
it.type = type
it.url = url
ConcreteNetManager.Notify.loadBind(it)
}
}
}
}
- use
class Use {
init {
ClientForNetMnager.Get()
ClientForNetMnager.Post()
ClientForNetMnager.Delete()
ClientForNetMnager.Update()
}
}
補(bǔ)充:本文type時(shí)String類型,當(dāng)你替換成enum在when的時(shí)候編譯器會(huì)自動(dòng)補(bǔ)充你所添加的所有網(wǎng)絡(luò)請(qǐng)求的枚舉,原文這樣寫(xiě)的原因很簡(jiǎn)單 -> 讓你有足夠的想象空間:比方說(shuō)(哪個(gè)美女..)