在我们实际开发当中,我们会用到MVP架构设计,而MVP架构设计按照传统开发,分为:
- M层:数据层->数据库、网络、文件…
- V层:UI层(UIView + UIViewController->创建UI、更新UI)
- P层:中介->Presenter(将M层和V层进行关联)
那么MVP与与中介者模式有什么关系呢?
首先中介者模式分为四种角色
角色一:抽象中介者->P层->MvpPresenterProtocol->协议
角色二:具体中介者->P层->LoginPresenter->具体实现类
角色三:抽象同事->M层+V层
ModelProtocol、MvpViewProtocol
角色四:具体同事->LoginModel、LoginView
上面四种角色分别担任不同的任务。角色一是抽象中介者,定义中介者担任的任务(协议);角色二是具体实现类,抽象中介者的实现类;角色三是抽象同事类;角色四是具体同事类,实现类
代码实现:
角色一:抽象中介者->P层->MvpPresenterProtocol->协议
//
// MvpPresenterProtocol.swift
// 中介者模式-Swift
import UIKit
//角色一:抽象中介者->P层->MvpPresenterProtocol->协议
//两个标准
//持有同事引用
protocol MvpPresenterProtocol {
//标准一:绑定V层(绑定引用)
func attachView(view:MvpViewProtocol)
//标准二:解绑V层(释放引用)
func detachView()
}
角色二:具体中介者->P层->LoginPresenter->具体实现类
//
// LoginPresenter.swift
// 中介者模式-Swift
//
import UIKit
//角色二:具体中介者->P层->LoginPresenter->具体实现类
//关联->持有引用
class LoginPresenter: MvpPresenterProtocol,CallBack {
private var model:LoginModel
private var view:LoginView?
init() {
self.model = LoginModel()
}
//随便举个例子(抽象)
func attachView(view: MvpViewProtocol) {
self.view = view as? LoginView
}
func detachView() {
self.view = nil
}
func login(name:String, Passwd:String) {
//业务逻辑
self.model.login(name: name, password: Passwd, callBack: self)
}
func onResult(result: Any?) {
self.view?.onLoginResult(result: result)
}
}
角色三:抽象同事->V层(最高层次协议,没有任何定义,只是一个规范)
//
// MvpViewProtocol.swift
// 中介者模式-Swift
import UIKit
//角色三:抽象同事->V层(最高层次协议,没有任何定义,只是一个规范)
protocol MvpViewProtocol {
}
角色三:抽象同事- M层
//
// ModelProtocol.swift
// 中介者模式-Swift
import Foundation
//角色三:抽象同事- M层
protocol ModelProtocol {
//看需求
}
角色四:具体同事->LoginModel
//
// LoginModel.swift
// 中介者模式-Swift
import UIKit
protocol CallBack {
func onResult(result:Any?)
}
//角色四:具体同事->LoginModel
class LoginModel: NSObject {
func login(name:String, password:String, callBack:CallBack) {
//发起请求->回调UI
//调用登录逻辑(数据库、网络、文件)
//...忽略100行代码
}
}
角色四:具体同事->LoginView
//
// LoginView.swift
// 中介者模式-Swift
import UIKit
//角色四:具体同事->LoginView
protocol LoginView: MvpViewProtocol {
func onLoginResult(result:Any?)
}
角色四:具体同事(MvpViewProtocol实现)->ViewController
//
// ViewController.swift
// 中介者模式-Swift
import UIKit
//角色四:具体同事(MvpViewProtocol实现)->ViewController
class ViewController: UIViewController,LoginView {
private var presenter:LoginPresenter?
override func viewDidLoad() {
super.viewDidLoad()
self.presenter = LoginPresenter()
//绑定
self.presenter?.attachView(view: self)
self.presenter?.login(name: "userName", Passwd: "Password")
//解绑(看你的需要->推出时候,页面暂停的时候)
self.presenter?.detachView()
}
//回调
func onLoginResult(result: Any?) {
print("success")
}
网友评论