Post

MVC 设计模式

MVC 设计模式

1. 什么是 MVC?

MVCModel-View-Controller)是一种将 数据、界面、逻辑 分离的架构模式。它将应用程序拆分为三个核心部分:

  • Model(模型层):负责数据管理,包括数据存储、处理和业务逻辑。
  • View(视图层):负责 UI 展示,与用户交互,但不包含业务逻辑。
  • Controller(控制器层):负责连接 Model 和 View,处理用户交互,并更新数据和 UI。

MVC 结构示意图:

1
2
3
+-----------+       +-----------+       +-----------+
|   Model   | <---> | Controller | <---> |   View    |
+-----------+       +-----------+       +-----------+

2. MVC 各部分详解(在Objective-C中的应用)

2.1 Model(模型层)

模型层 负责存储和管理数据。

示例:定义一个 User 模型类

1
2
3
4
5
6
7
@interface User : NSObject
@property (nonatomic, strong) NSString *name;
@property (nonatomic, assign) NSInteger age;
@end

@implementation User
@end

2.2 View(视图层)

视图层 负责 UI 展示,不包含业务逻辑。

示例:自定义一个 UserView

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
@interface UserView : UIView
@property (nonatomic, strong) UILabel *nameLabel;
@property (nonatomic, strong) UILabel *ageLabel;

- (void)updateWithUser:(User *)user;
@end

@implementation UserView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 200, 20)];
        self.ageLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 40, 200, 20)];
        [self addSubview:self.nameLabel];
        [self addSubview:self.ageLabel];
    }
    return self;
}

- (void)updateWithUser:(User *)user {
    self.nameLabel.text = user.name;
    self.ageLabel.text = [NSString stringWithFormat:@"%ld", (long)user.age];
}

@end

2.3 Controller(控制器层)

控制器层 负责处理用户交互,并更新 Model 和 View。

示例:UserViewController

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
@interface UserViewController : UIViewController
@property (nonatomic, strong) User *user;
@property (nonatomic, strong) UserView *userView;
@end

@implementation UserViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.user = [[User alloc] init];
    self.user.name = @"John Doe";
    self.user.age = 30;
    
    self.userView = [[UserView alloc] initWithFrame:self.view.bounds];
    [self.view addSubview:self.userView];
    
    [self.userView updateWithUser:self.user];
}

@end
This post is licensed under CC BY 4.0 by the author.