Kotlin enum (实现网络加载架构)
- 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()
}
}
补充:本文type时String类型,当你替换成enum在when的时候编译器会自动补充你所添加的所有网络请求的枚举,原文这样写的原因很简单 -> 让你有足够的想象空间:比方说(哪个美女..)