隨著開(kāi)發(fā)的迭代升級(jí)共苛,不斷增加新的功能和職責(zé),AppDelegate中的代碼量也不斷增長(zhǎng),致使Massive催首,而精通 OOP 的我們自然會(huì)想法子對(duì)其瘦身。
AppDelegate
什么是
AppDelegate
泄鹏?
-
AppDelegate
是應(yīng)用程序的根對(duì)象郎任,即唯一代理:
a、其提供應(yīng)用程序生命周期事件的暴露备籽。
b舶治、其確保應(yīng)用程序與系統(tǒng)以及其他應(yīng)用程序正確的交互。
c车猬、其通常承擔(dān)很多職責(zé)霉猛,這使得很難進(jìn)行更改,擴(kuò)展和測(cè)試珠闰。 - 作為連接應(yīng)用程序和系統(tǒng)的
協(xié)調(diào)者
惜浅,他應(yīng)該總是:
a、單一職責(zé)
b伏嗜、易于擴(kuò)展
c坛悉、易于測(cè)試
組合模式
- 組合模式依據(jù)樹(shù)形結(jié)構(gòu)來(lái)組合對(duì)象,用來(lái)表示部分以及整體層次承绸。
a裸影、它隸屬于結(jié)構(gòu)型模式
b、主要分??組裝類(lèi)
與??服務(wù)類(lèi)
c八酒、它近似于簡(jiǎn)易SOA - 其作用體現(xiàn)為
a空民、服務(wù)易插拔
b、無(wú)需額外改變AppDelegate
實(shí)踐環(huán)節(jié)
- 樹(shù)節(jié)點(diǎn)(根節(jié)點(diǎn)):
組裝類(lèi)
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface AppDelegateFactory : NSObject
@property (readonly) NSMutableArray *services;
+ (instancetype)standardFactory;
@end
NS_ASSUME_NONNULL_END
#import "AppDelegateFactory.h"
@interface AppDelegateFactory ()
@property (nonatomic, strong) NSMutableArray *services;
@end
@implementation AppDelegateFactory
+ (instancetype)standardFactory {
static AppDelegateFactory *insance = nil;
static dispatch_once_t once;
dispatch_once(&once, ^{
insance = [AppDelegateFactory new];
});
return insance;
}
- (instancetype)init
{
self = [super init];
if (self) {
makeDefault(self);
}
return self;
}
NS_INLINE void makeDefault(AppDelegateFactory *factory) {
[factory registeService:@"ComponentLaunchService"];
// [factory registeService:@"ComponentPushService"];
// [factory registeService:@"ComponentBackgroundService"];
}
- (void)registeService:(NSString *)serviceClassString {
Class targetClass = NSClassFromString(serviceClassString);
NSObject *service = [[targetClass alloc] init];
if (![self.services containsObject:service])
[self.services addObject:service];
}
#pragma mark - Lazy load
/**
生命流程中,我們有時(shí)候需要保持調(diào)用順序界轩,所以采用數(shù)組結(jié)構(gòu)
*/
- (NSMutableArray *)services {
if (!_services) {
_services = [NSMutableArray array];
}
return _services;
}
@end
- 子節(jié)點(diǎn)(功能單元):
服務(wù)類(lèi)
#import <UIKit/UIKit.h>
@interface ComponentLaunchService : NSObject <UIApplicationDelegate>
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions;
@end
@implementation ComponentLaunchService
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
/// launch your application
return YES;
}
- 植入流程
#import "AppDelegate.h"
#import "AppDelegateFactory.h"
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
id<UIApplicationDelegate> service;
for(service in [AppDelegateFactory standardFactory].services){
///若服務(wù)響應(yīng)
if ([service respondsToSelector:_cmd]) {
[service application:application didFinishLaunchingWithOptions:launchOptions];
}
}
[self.window makeKeyAndVisible];
return YES;
}
- (void)applicationDidEnterBackground:(UIApplication *)application {
id<UIApplicationDelegate> service;
for(service in [AppDelegateFactory standardFactory].services){
if ([service respondsToSelector:_cmd]){
[service applicationDidEnterBackground:application];
}
}
//程序進(jìn)入后臺(tái),通知服務(wù)器
}
- (void)applicationWillEnterForeground:(UIApplication *)application {
id<UIApplicationDelegate> service;
for(service in [AppDelegateFactory standardFactory].services){
if ([service respondsToSelector:_cmd]){
[service applicationWillEnterForeground:application];
}
}
//程序從后臺(tái)進(jìn)入前臺(tái)
}
- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application {
id<UIApplicationDelegate> service;
for(service in [AppDelegateFactory standardFactory].services){
if ([service respondsToSelector:_cmd]){
[service applicationDidReceiveMemoryWarning:application];
}
}
//收到內(nèi)存警告時(shí)
}
///..省略以下生命周期回調(diào)方法
@end
中介者模式
- 中介者模式提供一個(gè)中介類(lèi)画饥,該類(lèi)通常處理不同類(lèi)之間的通信。
a浊猾、其隸屬于行為型模式
b抖甘、支持松耦合 - 作用體現(xiàn)為:
a、使代碼易于維護(hù)
a葫慎、降低多個(gè)對(duì)象和類(lèi)之間的通信復(fù)雜性
實(shí)踐環(huán)節(jié)
- 定義UIApplication的生命周期監(jiān)聽(tīng)者
import UIKit
class AppLifecycleMediator: NSObject {
private var listeners: [AppLifecycleListener]
init(listeners: [AppLifecycleListener]) {
self.listeners = listeners
super.init()
subscribe()
}
deinit {
NotificationCenter.default.removeObserver(self)
}
private func subscribe() {
NotificationCenter.default.addObserver(self, selector: #selector(onAppDidFinishLaunching), name: UIApplication.didFinishLaunchingNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(onAppDidReceiveMemoryWarning), name: UIApplication.didReceiveMemoryWarningNotification, object: nil)
}
@objc private func onAppDidFinishLaunching() {
listeners.forEach { $0.onAppDidFinishLaunching() }
}
@objc func onAppDidReceiveMemoryWarning() {
listeners.forEach { $0.onAppDidReceiveMemoryWarning() }
}
}
- 定義監(jiān)聽(tīng)協(xié)議與實(shí)現(xiàn)者
import UIKit
protocol AppLifecycleListener {
func onAppDidFinishLaunching()
func onAppDidReceiveMemoryWarning()
}
extension AppLifecycleListener {
func onAppDidFinishLaunching() {}
func onAppDidReceiveMemoryWarning() {}
}
//MARK: - Listeners.. (舉個(gè)栗子)
class SocketListener: AppLifecycleListener {
func onAppDidFinishLaunching() {
print("[開(kāi)啟長(zhǎng)鏈接..]")
}
}
- 定義靜態(tài)方法衔彻,進(jìn)行初始化
extension AppLifecycleMediator {
static func makeDefaultMediator() -> AppLifecycleMediator {
let socketListener = SocketListener()
return AppLifecycleMediator(listeners: [socketListener])
}
}
- 植入中介人
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
// point code
let mediator = AppLifecycleMediator.makeDefaultMediator()
///省略以下內(nèi)容
}
優(yōu)點(diǎn)在于
- 僅需要一次初始化
- 中介類(lèi)自動(dòng)訂閱事件
- 監(jiān)聽(tīng)者
Listener
易于增減、對(duì)AppDelegate
侵入弱
其實(shí)我們對(duì)
AppDelegate
都是維系代碼可維護(hù)度偷办,職責(zé)的劃分艰额,保證不會(huì)在部分修改時(shí)牽一發(fā)而動(dòng)全身
,這樣使得代碼更靈活與茁壯椒涯,可隨時(shí)插拔與復(fù)用柄沮。
以上設(shè)計(jì)方式亦適用于,復(fù)雜模塊職能劃分废岂,本文僅做簡(jiǎn)單介紹與思考~??