MVP架构设计

2017-01-14  本文已影响104人  952625a28d0d

什么是MVC 什么是MVP

Paste_Image.png
#import <Foundation/Foundation.h>

// 定义回调Block
typedef void(^Callback)(NSString *result);

@interface HttpUtils : NSObject

+ (void)post:(NSString *)name pwd:(NSString *)pwd callback:(Callback)callback;

@end```

import "HttpUtils.h"

@implementation HttpUtils

// 发送Post请求

@end```

#import <Foundation/Foundation.h>
#import "HttpUtils.h"

@interface LoginModel : NSObject

- (void)login:(NSString *)name pwd:(NSString *)pwd callback:(Callback)callback;

@end```

import "LoginModel.h"

@implementation LoginModel

// Model层: 数据层
// 包含:数据库模块、网络模块、文件等

@end```

  数据解析
  数据存储等
#import <Foundation/Foundation.h>

// V层和M层交互遵循的协议
@protocol LoginView <NSObject>

// 登录回调
- (void)onLoginResult:(NSString *)result;

@end```

   - P层(Presenter)
     实现原理:
     M层和V层要进行关联,通过P层,那么如何通过P层来关联呢?
     P层要持有M层对象的引用(指针)。同时还需要持有V层对象的引用(指针)。再进行关联。所以我们需要对M层和V层进行绑定(重点是绑定V层)

import <Foundation/Foundation.h>

import "LoginView.h"

@interface LoginPresenter : NSObject

// 绑定V层

// 解除绑定

// 登录请求的方法(发起登陆)

@end```

#import "LoginPresenter.h"
#import "LoginModel.h"

@interface LoginPresenter()

// 持有M层的引用
@property (nonatomic, strong) LoginModel *loginModel;

// 持有V层的引用
@property (nonatomic) id<LoginView> loginView;

@end

@implementation LoginPresenter

- (instancetype)init{
    
    if (self = [super init]){
        // 初始化
        _loginModel = [[LoginModel alloc] init];
    };
    
    return self;
}

- (void)attachView:(id)view{
    _loginView = view;
}

- (void)detachView{
    _loginView = nil;
}

// 登录请求的方法 (发起登录)
- (void)login:(NSString *)name pwd:(NSString *)pwd{
    // 调用登录
    [_loginModel login:name pwd:pwd callback:^(NSString *result) {
        // 回调UI层
        [_loginView onLoginResult:result];
    }];
}

@end```

   - 在V层调用P层 (关联 发起获取数据的请求 在协议回到方法中获取结果)

import "ViewController.h"

import "LoginView.h"

import "LoginPresenter.h"

@interface ViewController ()<LoginView>

@property (nonatomic, strong) LoginPresenter *loginPresenter;

@end

@implementation ViewController

}

// 实现协议登录回调

@end```

上一篇 下一篇

猜你喜欢

热点阅读