MVP 模式
Model-View-Presenter(MVP)是(MVC)體系結(jié)構(gòu)模式的一種變體,并主要用于構(gòu)建用戶界面典蝌。在iOS,這個(gè)模式是使用一個(gè)協(xié)議實(shí)現(xiàn)的,協(xié)議定義了接口實(shí)現(xiàn)的委托粱快。
Presenter
在MVP模式中,協(xié)議是假定中間人的功能,所有表示邏輯被推到中間人中恬砂。
Controller v/s Presenter
-
V層
UIView和UIViewController以及子類
-
P層
中介(關(guān)聯(lián)M和V)
-
M層
數(shù)據(jù)層(數(shù)據(jù):數(shù)據(jù)庫(kù),網(wǎng)絡(luò),文件等等)
mvp.png
mvp-delegate.png
第一步:實(shí)現(xiàn)M層
#import "LoginModel.h"
//M層
@implementation LoginModel
- (void)loginWithName:(NSString*)name pwd:(NSString*)pwd callback:(Callback)callback{
//實(shí)現(xiàn)功能
//例如:訪問(wèn)網(wǎng)絡(luò)?訪問(wèn)數(shù)據(jù)庫(kù)?
//數(shù)據(jù)曾劃分了模塊()
[HttpUtils postWithName:name pwd:pwd callback:^(NSString *result) {
//解析json ,xml數(shù)據(jù)
//然后保存數(shù)據(jù)庫(kù)
//中間省略100行代碼
callback(result);//返回?cái)?shù)據(jù)回調(diào)
}];
}
@end
第二步:實(shí)現(xiàn)V層
#import <Foundation/Foundation.h>
//V層
@protocol LoginView <NSObject>
- (void)onLoginResult:(NSString*)result;
@end
第三步:實(shí)現(xiàn)P層
// P層
#import <Foundation/Foundation.h>
#import "LoginView.h"
#import "LoginModel.h"
//中介(用于關(guān)聯(lián)M層和V層)
@interface LoginPresenter : NSObject
//提供一個(gè)業(yè)務(wù)方法
- (void)loginWithName:(NSString*)name pwd:(NSString*)pwd;
- (void)attachView:(id<LoginView>)loginView;
- (void)detachView;
@end
#import "LoginPresenter.h"
//P是中介(職責(zé)是用于關(guān)聯(lián)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;
}
//實(shí)現(xiàn)業(yè)務(wù)方法
- (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];
//程序一旦運(yùn)行立馬執(zhí)行請(qǐng)求(測(cè)試)(按鈕或者事件)
[_presenter loginWithName:@"188*****8*8" pwd:@"123456"];
}
- (void)onLoginResult:(NSString *)result{
NSLog(@"返回結(jié)果%@",result);
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
[_presenter detachView];
}
@end
這樣一個(gè)簡(jiǎn)單的MVP模式的邏輯就完成了,這里有寶藏Demo,如果覺(jué)得有幫助,不要忘記點(diǎn)個(gè)star哦!