设计思路
- 抽象基类:创建一个抽象的视图控制器基类,定义数据加载、数据处理和数据展示的模板方法。其中,数据加载、数据处理和数据展示的具体实现设为抽象方法,由子类根据自身需求实现。
- 子类继承:各个具体的视图控制器子类继承自该抽象基类,实现基类中定义的抽象方法,以满足各自不同的数据来源、处理逻辑和展示方式。
关键代码实现
- 抽象基类定义
#import <UIKit/UIKit.h>
@interface BaseViewController : UIViewController
// 模板方法,控制整体流程
- (void)loadAndShowData {
[self loadData];
[self processData];
[self showData];
}
// 抽象方法,由子类实现
- (void)loadData;
- (void)processData;
- (void)showData;
@end
- 子类实现示例
#import "BaseViewController.h"
@interface SpecificViewController : BaseViewController
@end
@implementation SpecificViewController
- (void)loadData {
// 具体的数据加载逻辑,例如从网络请求数据
NSLog(@"Load data from network in SpecificViewController");
}
- (void)processData {
// 具体的数据处理逻辑
NSLog(@"Process data in SpecificViewController");
}
- (void)showData {
// 具体的数据展示逻辑,例如更新UI
NSLog(@"Show data in SpecificViewController");
}
@end
- 使用示例
#import "SpecificViewController.h"
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@end
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
SpecificViewController *vc = [[SpecificViewController alloc] init];
UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:vc];
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
self.window.rootViewController = nav;
[self.window makeKeyAndVisible];
[vc loadAndShowData];
return YES;
}
@end