MVP 模式
Model-View-Presenter(MVP)是(MVC)體系結構模式的一種變體,并主要用于構建用戶界面。在iOS,這個模式是使用一個協議實現的,協議定義了接口實現的委托。
Presenter
在MVP模式中,協議是假定中間人的功能,所有表示邏輯被推到中間人中。
Controller v/s Presenter
-
V層
UIView和UIViewController以及子類
-
P層
中介(關聯M和V)
-
M層
數據層(數據:數據庫,網絡,文件等等)
mvp.png
mvp-delegate.png
第一步:實現M層
#import "LoginModel.h"
//M層
@implementation LoginModel
- (void)loginWithName:(NSString*)name pwd:(NSString*)pwd callback:(Callback)callback{
//實現功能
//例如:訪問網絡?訪問數據庫?
//數據曾劃分了模塊()
[HttpUtils postWithName:name pwd:pwd callback:^(NSString *result) {
//解析json ,xml數據
//然后保存數據庫
//中間省略100行代碼
callback(result);//返回數據回調
}];
}
@end
第二步:實現V層
#import <Foundation/Foundation.h>
//V層
@protocol LoginView <NSObject>
- (void)onLoginResult:(NSString*)result;
@end
第三步:實現P層
// P層
#import <Foundation/Foundation.h>
#import "LoginView.h"
#import "LoginModel.h"
//中介(用于關聯M層和V層)
@interface LoginPresenter : NSObject
//提供一個業務方法
- (void)loginWithName:(NSString*)name pwd:(NSString*)pwd;
- (void)attachView:(id<LoginView>)loginView;
- (void)detachView;
@end
#import "LoginPresenter.h"
//P是中介(職責是用于關聯M和V)
//P層需要:持有M層的引用和V層的引用(OOP)思想
@interface LoginPresenter ()
@property (nonatomic,strong) LoginModel *loginModel;
@property (nonatomic,strong) id<LoginView> loginView;
@end
@implementation LoginPresenter
- (instancetype)init{
self = [super init];
if (self) {
//持有M層的引用
_loginModel = [[LoginModel alloc]init];
}
return self;
}
//提供綁定V層方法
//綁定
- (void)attachView:(id<LoginView>)loginView{
_loginView = loginView;
}
//解除綁定
- (void)detachView{
_loginView = nil;
}
//實現業務方法
- (void)loginWithName:(NSString*)name pwd:(NSString*)pwd{
[_loginModel loginWithName:name pwd:pwd callback:^(NSString *result) {
if (_loginView != nil) {
[_loginView onLoginResult:result];
}
}];
}
@end
第四步:在VIewController中使用
#import "ViewController.h"
#import "LoginView.h"
#import "LoginPresenter.h"
@interface ViewController ()<LoginView>
@property (nonatomic,strong) LoginPresenter* presenter;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
_presenter = [[LoginPresenter alloc ]init];
[_presenter attachView:self];
//程序一旦運行立馬執行請求(測試)(按鈕或者事件)
[_presenter loginWithName:@"188*****8*8" pwd:@"123456"];
}
- (void)onLoginResult:(NSString *)result{
NSLog(@"返回結果%@",result);
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
[_presenter detachView];
}
@end
這樣一個簡單的MVP模式的邏輯就完成了,這里有寶藏Demo,如果覺得有幫助,不要忘記點個star哦!