引言
在iOS开发的世界里,Objective - C作为一门经典的编程语言,其底层架构设计和设计模式对于构建高质量、可维护和可扩展的应用程序起着至关重要的作用。深入理解Objective - C的底层架构和设计模式,不仅能够帮助开发者更好地应对各种复杂的开发场景,还能提升代码的质量和性能。本文将深入探讨Objective - C底层架构设计和设计模式的相关知识点,结合具体的例子进行详细阐述。
一、架构设计基础概念
1.1 分层架构
分层架构是一种常见的架构设计模式,它将应用程序按照功能划分为不同的层次,每个层次负责特定的职责,层次之间通过接口进行交互。常见的分层架构有三层架构,包括表示层、业务逻辑层和数据访问层。
表示层(Presentation Layer)
表示层负责与用户进行交互,展示数据和接收用户输入。在iOS开发中,通常由视图控制器(ViewController)和视图(View)组成。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| // 表示层示例:ViewController #import "ViewController.h" #import "UserViewModel.h"
@interface ViewController () @property (nonatomic, strong) UserViewModel *viewModel; @end
@implementation ViewController
- (void)viewDidLoad { [super viewDidLoad]; self.viewModel = [[UserViewModel alloc] init]; [self.viewModel fetchUserInfoWithCompletion:^(NSString *userName) { // 更新UI self.title = userName; }]; }
@end
|
业务逻辑层(Business Logic Layer)
业务逻辑层负责处理应用程序的业务逻辑,如数据验证、计算等。在上面的例子中,UserViewModel
就属于业务逻辑层。
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 27
| // 业务逻辑层示例:UserViewModel #import "UserViewModel.h" #import "UserService.h"
@interface UserViewModel () @property (nonatomic, strong) UserService *userService; @end
@implementation UserViewModel
- (instancetype)init { self = [super init]; if (self) { self.userService = [[UserService alloc] init]; } return self; }
- (void)fetchUserInfoWithCompletion:(void(^)(NSString *userName))completion { [self.userService getUserInfoWithCompletion:^(NSString *userName) { if (completion) { completion(userName); } }]; }
@end
|
数据访问层(Data Access Layer)
数据访问层负责与数据源进行交互,如数据库、网络等。在上面的例子中,UserService
就属于数据访问层。
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 27 28 29
| // 数据访问层示例:UserService #import "UserService.h"
@interface UserService ()
@end
@implementation UserService
- (void)getUserInfoWithCompletion:(void(^)(NSString *userName))completion { // 模拟网络请求 [self simulateNetworkRequestWithCompletion:^(NSDictionary *response) { NSString *userName = response[@"userName"]; if (completion) { completion(userName); } }]; }
- (void)simulateNetworkRequestWithCompletion:(void(^)(NSDictionary *response))completion { dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ NSDictionary *response = @{@"userName": @"John Doe"}; if (completion) { completion(response); } }); }
@end
|
1.2 模块化架构
模块化架构将应用程序拆分为多个独立的模块,每个模块具有独立的功能和职责。模块之间通过接口进行通信,降低了模块之间的耦合度,提高了代码的可维护性和可扩展性。
模块划分原则
- 功能内聚:每个模块应该具有明确的功能,模块内部的代码应该紧密相关。
- 低耦合:模块之间的依赖关系应该尽量简单,避免模块之间的强耦合。
示例:一个电商应用可以划分为商品模块、订单模块、用户模块等。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| // 商品模块接口 @protocol ProductModuleProtocol <NSObject>
- (void)showProductDetailWithProductID:(NSString *)productID;
@end
// 商品模块实现 @interface ProductModule : NSObject <ProductModuleProtocol>
@end
@implementation ProductModule
- (void)showProductDetailWithProductID:(NSString *)productID { // 显示商品详情页 NSLog(@"Showing product detail for product ID: %@", productID); }
@end
|
1.3 微服务架构
微服务架构是一种将应用程序拆分为多个小型、自治的服务的架构模式。每个服务都可以独立开发、部署和扩展,通过网络进行通信。在iOS开发中,微服务架构通常用于与后端服务进行交互。
示例:一个社交应用可以将用户服务、消息服务、好友服务等拆分为独立的微服务。
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 27 28 29 30 31 32 33
| // 用户服务接口 @protocol UserServiceProtocol <NSObject>
- (void)getUserInfoWithUserID:(NSString *)userID completion:(void(^)(NSDictionary *userInfo))completion;
@end
// 用户服务实现 @interface UserService : NSObject <UserServiceProtocol>
@end
@implementation UserService
- (void)getUserInfoWithUserID:(NSString *)userID completion:(void(^)(NSDictionary *userInfo))completion { // 模拟网络请求获取用户信息 [self simulateNetworkRequestWithUserID:userID completion:^(NSDictionary *response) { if (completion) { completion(response); } }]; }
- (void)simulateNetworkRequestWithUserID:(NSString *)userID completion:(void(^)(NSDictionary *response))completion { dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ NSDictionary *response = @{@"userID": userID, @"userName": @"John Doe"}; if (completion) { completion(response); } }); }
@end
|
二、常见架构模式
2.1 MVC(Model - View - Controller)
MVC是一种经典的架构模式,它将应用程序分为三个主要部分:模型(Model)、视图(View)和控制器(Controller)。
模型(Model)
模型负责存储和管理应用程序的数据和业务逻辑。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| // 模型示例:UserModel @interface UserModel : NSObject
@property (nonatomic, strong) NSString *userName; @property (nonatomic, strong) NSString *userID;
- (instancetype)initWithUserName:(NSString *)userName userID:(NSString *)userID;
@end
@implementation UserModel
- (instancetype)initWithUserName:(NSString *)userName userID:(NSString *)userID { self = [super init]; if (self) { self.userName = userName; self.userID = userID; } return self; }
@end
|
视图(View)
视图负责显示数据和接收用户输入。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| // 视图示例:UserView @interface UserView : UIView
@property (nonatomic, strong) UILabel *userNameLabel;
@end
@implementation UserView
- (instancetype)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { self.userNameLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 200, 30)]; [self addSubview:self.userNameLabel]; } return self; }
@end
|
控制器(Controller)
控制器负责协调模型和视图之间的交互。
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 27 28 29 30 31 32 33 34 35 36
| // 控制器示例:UserViewController @interface UserViewController : UIViewController
@property (nonatomic, strong) UserModel *userModel; @property (nonatomic, strong) UserView *userView;
@end
@implementation UserViewController
- (void)viewDidLoad { [super viewDidLoad]; [self fetchUserInfo]; }
- (void)fetchUserInfo { [self simulateNetworkRequestWithCompletion:^(NSDictionary *response) { NSString *userName = response[@"userName"]; NSString *userID = response[@"userID"]; self.userModel = [[UserModel alloc] initWithUserName:userName userID:userID]; self.userView = [[UserView alloc] initWithFrame:self.view.bounds]; [self.view addSubview:self.userView]; self.userView.userNameLabel.text = self.userModel.userName; }]; }
- (void)simulateNetworkRequestWithCompletion:(void(^)(NSDictionary *response))completion { dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ NSDictionary *response = @{@"userName": @"John Doe", @"userID": @"123"}; if (completion) { completion(response); } }); }
@end
|
2.2 MVVM(Model - View - ViewModel)
MVVM是在MVC基础上发展而来的架构模式,它引入了视图模型(ViewModel)来处理视图的显示逻辑。
视图模型(ViewModel)
视图模型负责将模型数据转换为视图可以显示的格式,并处理视图的交互逻辑。
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 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
| // 视图模型示例:UserViewModel @interface UserViewModel : NSObject
@property (nonatomic, strong) UserModel *userModel; @property (nonatomic, strong) NSString *displayName;
- (instancetype)initWithUserModel:(UserModel *)userModel; - (void)fetchUserInfoWithCompletion:(void(^)(void))completion;
@end
@implementation UserViewModel
- (instancetype)initWithUserModel:(UserModel *)userModel { self = [super init]; if (self) { self.userModel = userModel; self.displayName = [NSString stringWithFormat:@"Name: %@", userModel.userName]; } return self; }
- (void)fetchUserInfoWithCompletion:(void(^)(void))completion { [self simulateNetworkRequestWithCompletion:^(NSDictionary *response) { NSString *userName = response[@"userName"]; NSString *userID = response[@"userID"]; self.userModel = [[UserModel alloc] initWithUserName:userName userID:userID]; self.displayName = [NSString stringWithFormat:@"Name: %@", self.userModel.userName]; if (completion) { completion(); } }]; }
- (void)simulateNetworkRequestWithCompletion:(void(^)(NSDictionary *response))completion { dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ NSDictionary *response = @{@"userName": @"John Doe", @"userID": @"123"}; if (completion) { completion(response); } }); }
@end
|
视图和控制器
视图和控制器的职责与MVC类似,但视图和控制器的耦合度更低,通过视图模型进行数据绑定。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| // 视图控制器示例:UserViewController @interface UserViewController : UIViewController
@property (nonatomic, strong) UserViewModel *userViewModel; @property (nonatomic, strong) UserView *userView;
@end
@implementation UserViewController
- (void)viewDidLoad { [super viewDidLoad]; self.userViewModel = [[UserViewModel alloc] initWithUserModel:nil]; [self.userViewModel fetchUserInfoWithCompletion:^{ self.userView = [[UserView alloc] initWithFrame:self.view.bounds]; [self.view addSubview:self.userView]; self.userView.userNameLabel.text = self.userViewModel.displayName; }]; }
@end
|
2.3 MVP(Model - View - Presenter)
MVP将视图和业务逻辑分离,通过Presenter来协调两者之间的交互。
视图(View)
视图负责显示数据和接收用户输入,并将用户操作传递给Presenter。
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 27 28 29
| // 视图示例:UserView @protocol UserViewProtocol <NSObject>
- (void)displayUserName:(NSString *)userName;
@end
@interface UserView : UIView <UserViewProtocol>
@property (nonatomic, strong) UILabel *userNameLabel;
@end
@implementation UserView
- (instancetype)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { self.userNameLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 200, 30)]; [self addSubview:self.userNameLabel]; } return self; }
- (void)displayUserName:(NSString *)userName { self.userNameLabel.text = userName; }
@end
|
呈现器(Presenter)
Presenter负责处理业务逻辑,并更新视图。
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 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| // 呈现器示例:UserPresenter @interface UserPresenter : NSObject
@property (nonatomic, weak) id<UserViewProtocol> view; @property (nonatomic, strong) UserModel *userModel;
- (instancetype)initWithView:(id<UserViewProtocol>)view; - (void)fetchUserInfo;
@end
@implementation UserPresenter
- (instancetype)initWithView:(id<UserViewProtocol>)view { self = [super init]; if (self) { self.view = view; } return self; }
- (void)fetchUserInfo { [self simulateNetworkRequestWithCompletion:^(NSDictionary *response) { NSString *userName = response[@"userName"]; NSString *userID = response[@"userID"]; self.userModel = [[UserModel alloc] initWithUserName:userName userID:userID]; if (self.view) { [self.view displayUserName:self.userModel.userName]; } }]; }
- (void)simulateNetworkRequestWithCompletion:(void(^)(NSDictionary *response))completion { dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ NSDictionary *response = @{@"userName": @"John Doe", @"userID": @"123"}; if (completion) { completion(response); } }); }
@end
|
视图控制器
视图控制器负责创建Presenter和视图,并进行初始化。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| // 视图控制器示例:UserViewController @interface UserViewController : UIViewController
@property (nonatomic, strong) UserView *userView; @property (nonatomic, strong) UserPresenter *userPresenter;
@end
@implementation UserViewController
- (void)viewDidLoad { [super viewDidLoad]; self.userView = [[UserView alloc] initWithFrame:self.view.bounds]; [self.view addSubview:self.userView]; self.userPresenter = [[UserPresenter alloc] initWithView:self.userView]; [self.userPresenter fetchUserInfo]; }
@end
|
2.4 VIPER(View - Interactor - Presenter - Entity - Router)
VIPER是一种更复杂的架构模式,它将应用程序分为五个部分:视图(View)、交互器(Interactor)、呈现器(Presenter)、实体(Entity)和路由器(Router)。
实体(Entity)
实体负责存储应用程序的基本数据模型。
1 2 3 4 5 6 7 8 9 10 11
| // 实体示例:UserEntity @interface UserEntity : NSObject
@property (nonatomic, strong) NSString *userName; @property (nonatomic, strong) NSString *userID;
@end
@implementation UserEntity
@end
|
交互器(Interactor)
交互器负责处理业务逻辑和数据访问。
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 27 28 29 30 31 32
| // 交互器示例:UserInteractor @interface UserInteractor : NSObject
@property (nonatomic, strong) UserEntity *userEntity;
- (void)fetchUserInfoWithCompletion:(void(^)(UserEntity *userEntity))completion;
@end
@implementation UserInteractor
- (void)fetchUserInfoWithCompletion:(void(^)(UserEntity *userEntity))completion { [self simulateNetworkRequestWithCompletion:^(NSDictionary *response) { UserEntity *userEntity = [[UserEntity alloc] init]; userEntity.userName = response[@"userName"]; userEntity.userID = response[@"userID"]; if (completion) { completion(userEntity); } }]; }
- (void)simulateNetworkRequestWithCompletion:(void(^)(NSDictionary *response))completion { dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ NSDictionary *response = @{@"userName": @"John Doe", @"userID": @"123"}; if (completion) { completion(response); } }); }
@end
|
呈现器(Presenter)
Presenter负责协调视图和交互器之间的交互。
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 27 28 29
| // 呈现器示例:UserPresenter @protocol UserViewProtocol;
@interface UserPresenter : NSObject
@property (nonatomic, weak) id<UserViewProtocol> view; @property (nonatomic, strong) UserInteractor *userInteractor;
- (void)viewDidLoad;
@end
@protocol UserViewProtocol <NSObject>
- (void)displayUserInfo:(UserEntity *)userEntity;
@end
@implementation UserPresenter
- (void)viewDidLoad { [self.userInteractor fetchUserInfoWithCompletion:^(UserEntity *userEntity) { if (self.view) { [self.view displayUserInfo:userEntity]; } }]; }
@end
|
视图(View)
视图负责显示数据和接收用户输入。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| // 视图示例:UserView @interface UserView : UIView <UserViewProtocol>
@property (nonatomic, strong) UILabel *userNameLabel;
@end
@implementation UserView
- (instancetype)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { self.userNameLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 200, 30)]; [self addSubview:self.userNameLabel]; } return self; }
- (void)displayUserInfo:(UserEntity *)userEntity { self.userNameLabel.text = userEntity.userName; }
@end
|
路由器(Router)
路由器负责处理视图之间的导航。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| // 路由器示例:UserRouter @interface UserRouter : NSObject
+ (void)presentUserViewControllerFromViewController:(UIViewController *)viewController;
@end
@implementation UserRouter
+ (void)presentUserViewControllerFromViewController:(UIViewController *)viewController { UserViewController *userViewController = [[UserViewController alloc] init]; [viewController presentViewController:userViewController animated:YES completion:nil]; }
@end
|
视图控制器
视图控制器负责创建和协调VIPER组件。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| // 视图控制器示例:UserViewController @interface UserViewController : UIViewController
@property (nonatomic, strong) UserView *userView; @property (nonatomic, strong) UserPresenter *userPresenter; @property (nonatomic, strong) UserInteractor *userInteractor;
@end
@implementation UserViewController
- (void)viewDidLoad { [super viewDidLoad]; self.userView = [[UserView alloc] initWithFrame:self.view.bounds]; [self.view addSubview:self.userView]; self.userInteractor = [[UserInteractor alloc] init]; self.userPresenter = [[UserPresenter alloc] init]; self.userPresenter.view = self.userView; self.userPresenter.userInteractor = self.userInteractor; [self.userPresenter viewDidLoad]; }
@end
|
三、组件化架构
3.1 组件化概述
组件化架构是将一个大型应用拆分成多个独立的组件,每个组件可以独立开发、测试和维护。组件之间通过接口进行通信,降低了组件之间的耦合度,提高了代码的可维护性和可扩展性。在iOS开发中,组件化可以将不同的业务模块拆分成独立的组件,例如用户模块、商品模块、订单模块等。
3.2 组件化的实现方式
3.2.1 基于URL路由的组件化
通过URL路由的方式实现组件之间的通信,每个组件可以注册自己的URL,当需要调用某个组件时,通过URL进行跳转。
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 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
| // 路由管理类 @interface RouterManager : NSObject
+ (instancetype)sharedManager; - (void)registerURLPattern:(NSString *)pattern handler:(void (^)(NSDictionary *parameters))handler; - (BOOL)openURL:(NSString *)url;
@end
@implementation RouterManager
+ (instancetype)sharedManager { static RouterManager *sharedManager = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ sharedManager = [[RouterManager alloc] init]; }); return sharedManager; }
- (instancetype)init { self = [super init]; if (self) { self.routeHandlers = [NSMutableDictionary dictionary]; } return self; }
- (void)registerURLPattern:(NSString *)pattern handler:(void (^)(NSDictionary *parameters))handler { if (pattern && handler) { self.routeHandlers[pattern] = handler; } }
- (BOOL)openURL:(NSString *)url { NSURL *nsURL = [NSURL URLWithString:url]; NSString *host = nsURL.host; NSString *query = nsURL.query; NSDictionary *parameters = [self parseQueryString:query]; void (^handler)(NSDictionary *parameters) = self.routeHandlers[host]; if (handler) { handler(parameters); return YES; } return NO; }
- (NSDictionary *)parseQueryString:(NSString *)query { NSMutableDictionary *parameters = [NSMutableDictionary dictionary]; if (query.length > 0) { NSArray *pairs = [query componentsSeparatedByString:@"&"]; for (NSString *pair in pairs) { NSArray *keyValue = [pair componentsSeparatedByString:@"="]; if (keyValue.count == 2) { NSString *key = keyValue[0]; NSString *value = keyValue[1]; parameters[key] = value; } } } return parameters; }
@end
|
3.2.2 基于协议的组件化
通过定义协议的方式实现组件之间的通信,每个组件实现自己的协议,其他组件通过协议来调用该组件的功能。
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 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
| // 组件协议 @protocol UserComponentProtocol <NSObject>
- (void)showUserProfileWithUserID:(NSString *)userID;
@end
// 用户组件实现 @interface UserComponent : NSObject <UserComponentProtocol>
@end
@implementation UserComponent
- (void)showUserProfileWithUserID:(NSString *)userID { NSLog(@"Showing user profile for user ID: %@", userID); }
@end
// 组件管理类 @interface ComponentManager : NSObject
+ (instancetype)sharedManager; - (void)registerComponent:(id)component forProtocol:(Protocol *)protocol; - (id)getComponentForProtocol:(Protocol *)protocol;
@end
@implementation ComponentManager
+ (instancetype)sharedManager { static ComponentManager *sharedManager = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ sharedManager = [[ComponentManager alloc] init]; }); return sharedManager; }
- (instancetype)init { self = [super init]; if (self) { self.componentMap = [NSMutableDictionary dictionary]; } return self; }
- (void)registerComponent:(id)component forProtocol:(Protocol *)protocol { if (component && protocol) { NSString *protocolName = NSStringFromProtocol(protocol); self.componentMap[protocolName] = component; } }
- (id)getComponentForProtocol:(Protocol *)protocol { NSString *protocolName = NSStringFromProtocol(protocol); return self.componentMap[protocolName]; }
@end
|
3.3 组件化示例
假设我们有一个电商应用,包含商品模块和用户模块,我们可以将这两个模块拆分成独立的组件。
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 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
| // 商品模块 @interface ProductComponent : NSObject
- (void)showProductList;
@end
@implementation ProductComponent
- (void)showProductList { NSLog(@"Showing product list"); }
@end
// 用户模块 @interface UserComponent : NSObject
- (void)showUserLogin;
@end
@implementation UserComponent
- (void)showUserLogin { NSLog(@"Showing user login page"); }
@end
// 在AppDelegate中注册组件 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { [ComponentManager.sharedManager registerComponent:[[ProductComponent alloc] init] forProtocol:@protocol(ProductComponentProtocol)]; [ComponentManager.sharedManager registerComponent:[[UserComponent alloc] init] forProtocol:@protocol(UserComponentProtocol)]; return YES; }
// 在其他地方调用组件功能 id<ProductComponentProtocol> productComponent = [ComponentManager.sharedManager getComponentForProtocol:@protocol(ProductComponentProtocol)]; [productComponent showProductList];
id<UserComponentProtocol> userComponent = [ComponentManager.sharedManager getComponentForProtocol:@protocol(UserComponentProtocol)]; [userComponent showUserLogin];
|
四、设计模式
4.1 单例模式
单例模式确保一个类只有一个实例,并提供一个全局访问点。在iOS开发中,单例模式常用于管理共享资源,如网络请求管理器、数据库管理器等。
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 27 28 29 30 31 32
| // 单例模式示例:NetworkManager @interface NetworkManager : NSObject
+ (instancetype)sharedManager;
- (void)sendRequestWithURL:(NSString *)url completion:(void(^)(NSData *data, NSError *error))completion;
@end
@implementation NetworkManager
+ (instancetype)sharedManager { static NetworkManager *sharedManager = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ sharedManager = [[NetworkManager alloc] init]; }); return sharedManager; }
- (void)sendRequestWithURL:(NSString *)url completion:(void(^)(NSData *data, NSError *error))completion { // 模拟网络请求 NSURL *requestURL = [NSURL URLWithString:url]; NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithURL:requestURL completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { if (completion) { completion(data, error); } }]; [task resume]; }
@end
|
4.2 观察者模式
观察者模式定义了一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖它的对象都会得到通知并自动更新。在iOS开发中,NSNotificationCenter
就是一个典型的观察者模式的实现。
1 2 3 4 5 6 7 8 9 10
| // 观察者模式示例:通知中心 // 发布通知 [[NSNotificationCenter defaultCenter] postNotificationName:@"DataUpdatedNotification" object:nil userInfo:@{@"data": @"New Data"}];
// 注册观察者 [[NSNotificationCenter defaultCenter] addObserverForName:@"DataUpdatedNotification" object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) { NSDictionary *userInfo = note.userInfo; NSString *data = userInfo[@"data"]; NSLog(@"Received updated data: %@", data); }];
|
4.3 工厂模式
工厂模式是一种创建对象的设计模式,它将对象的创建和使用分离,通过一个工厂类来创建对象。在iOS开发中,工厂模式常用于创建不同类型的视图、控制器等。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| // 工厂模式示例:视图工厂 @interface ViewFactory : NSObject
+ (UIView *)createViewWithType:(NSString *)type;
@end
@implementation ViewFactory
+ (UIView *)createViewWithType:(NSString *)type { if ([type isEqualToString:@"redView"]) { UIView *redView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)]; redView.backgroundColor = [UIColor redColor]; return redView; } else if ([type isEqualToString:@"blueView"]) { UIView *blueView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)]; blueView.backgroundColor = [UIColor blueColor]; return blueView; } return nil; }
@end
|
4.4 代理模式
代理模式是一种对象行为模式,它允许一个对象将某些任务委托给另一个对象来完成。在iOS开发中,代理模式常用于处理用户交互、数据传递等。
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 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
| // 代理模式示例:协议和代理 @protocol CustomViewDelegate <NSObject>
- (void)customViewDidTap:(id)customView;
@end
@interface CustomView : UIView
@property (nonatomic, weak) id<CustomViewDelegate> delegate;
@end
@implementation CustomView
- (instancetype)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)]; [self addGestureRecognizer:tapGesture]; } return self; }
- (void)handleTap:(UITapGestureRecognizer *)gesture { if ([self.delegate respondsToSelector:@selector(customViewDidTap:)]) { [self.delegate customViewDidTap:self]; } }
@end
// 使用代理 @interface ViewController () <CustomViewDelegate>
@end
@implementation ViewController
- (void)viewDidLoad { [super viewDidLoad]; CustomView *customView = [[CustomView alloc] initWithFrame:CGRectMake(100, 100, 100, 100)]; customView.delegate = self; [self.view addSubview:customView]; }
- (void)customViewDidTap:(id)customView { NSLog(@"Custom view was tapped"); }
@end
|
4.5 装饰器模式
装饰器模式允许向一个现有的对象添加新的功能,同时又不改变其结构。在iOS开发中,装饰器模式可以用于动态地给视图添加额外的功能,如边框、阴影等。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| // 装饰器模式示例:视图装饰器 @interface ViewDecorator : UIView
@property (nonatomic, strong) UIView *decoratedView;
- (instancetype)initWithView:(UIView *)view;
@end
@implementation ViewDecorator
- (instancetype)initWithView:(UIView *)view { self = [super initWithFrame:view.frame]; if (self) { self.decoratedView = view; [self addSubview:view]; // 添加装饰效果,如边框 self.layer.borderColor = [UIColor blackColor].CGColor; self.layer.borderWidth = 1.0; } return self; }
@end
|
五、设计模式的原则
5.1 单一职责原则(SRP)
一个类应该只有一个引起它变化的原因。在iOS开发中,例如一个视图控制器只负责处理视图的显示和用户交互,而不负责数据的获取和处理。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| // 单一职责原则示例:ViewController @interface ViewController : UIViewController
@property (nonatomic, strong) UIButton *button;
@end
@implementation ViewController
- (void)viewDidLoad { [super viewDidLoad]; self.button = [UIButton buttonWithType:UIButtonTypeSystem]; self.button.frame = CGRectMake(100, 100, 100, 50); [self.button setTitle:@"Click Me" forState:UIControlStateNormal]; [self.button addTarget:self action:@selector(buttonTapped) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:self.button]; }
- (void)buttonTapped { // 只处理按钮点击的UI交互 NSLog(@"Button tapped"); }
@end
|
5.2 开放 - 封闭原则(OCP)
软件实体(类、模块、函数等)应该对扩展开放,对修改关闭。在iOS开发中,可以通过使用协议和继承来实现开放 - 封闭原则。
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 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
| // 开放 - 封闭原则示例:图形绘制 @protocol ShapeProtocol <NSObject>
- (void)draw;
@end
@interface Circle : NSObject <ShapeProtocol>
@end
@implementation Circle
- (void)draw { NSLog(@"Drawing a circle"); }
@end
@interface Rectangle : NSObject <ShapeProtocol>
@end
@implementation Rectangle
- (void)draw { NSLog(@"Drawing a rectangle"); }
@end
// 新增三角形 @interface Triangle : NSObject <ShapeProtocol>
@end
@implementation Triangle
- (void)draw { NSLog(@"Drawing a triangle"); }
@end
|
5.3 里氏替换原则(LSP)
子类可以替换其父类并且出现在父类能够出现的任何地方。在iOS开发中,例如自定义的视图类可以替换其父类 UIView
。
1 2 3 4 5 6 7 8 9 10 11
| // 里氏替换原则示例:自定义视图 @interface CustomView : UIView
@end
@implementation CustomView
@end
// 在使用UIView的地方可以使用CustomView UIView *view = [[CustomView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
|
5.4 接口隔离原则(ISP)
客户端不应该依赖它不需要的接口。在iOS开发中,例如一个视图控制器只需要实现它需要的协议方法。
1 2 3 4 5 6 7 8 9
| // 接口隔离原则示例:协议 @protocol DataSourceProtocol <NSObject>
- (NSInteger)numberOfItems; - (id)itemAtIndex:(NSInteger)index;
@end
@protocol DelegateProtocol <
|