ios開發:代理設計模式,ios開發設計模式
代理是一種簡單而功能強大的設計模式,這種模式用於一個對象“代表”另外一個對象去做和實現一些東西。 主對象維護一個代理(delegate)的引用並且在合適的時候向這個代理髮送訊息,這個訊息通知“代理”對象即將處理或是已經處理完了某一個事件。這個代理可以通過更新自己或是其它對象的UI介面或是其它狀態來響應主對象所發送過來的這個事件的訊息。或是在某些情況下能返回一個值來影響其它即將發生的事件該如何來處理。代理的主要價值是它可以讓你容易的定製各種對象的行為。
為了方便大家理解,我在這裡舉了個簡單的例子,有這樣一個情景:一個家庭裡有一個孩子,很小還不會吃飯,所以在餓了的時候需要媽媽來喂。在這裡我們把孩子當作一個主對象,媽媽當作代理對象看一下代理模式的實現。
直接來看一下代碼
TestDelegate.h
@protocol TestDelegate@required-(void)feetBaby;@optional-(void)playWithBaby;@end
在這裡定義了一個代理TestDelegate 注意到代理函數分為@required和@optional兩種,前者是必須實現的函數,後者是選擇性實現的函數
Baby.h
#import <Foundation/Foundation.h>#import "TestDelegate.h"@interface Baby : NSObject{ }@property(nonatomic)NSString* name;@property(nonatomic,retain)id<TestDelegate>delegate;+(Baby*)initWithName:(NSString*)str;-(void)hungry;@end
在baby.h中定義了一個delegate對象 並使他的類型為id 因為不知道哪個類的對象會接受這個代理並實現代理函數 所以定義為id類型
Baby.m
#import "Baby.h"@implementation Baby@synthesize name;@synthesize delegate;+(Baby*)initWithName:(NSString *)str{ Baby* baby = [[Baby alloc]init]; baby.name = str; return baby;}-(void)hungry{ NSLog(@"%@ is hungry",self.name); [delegate feetBaby];}@end
在baby.m中 寫了hungry函數 ,因為孩子在餓了的時候 會叫著要吃飯 ,雖然自己不會吃 ,但是知道有人會來喂他,而且不知道這個人是誰,所以在hungry中調用[delegate feetBaby]; 意為讓接受了TestDelegate並實現了feetBaby方法的對象來喂孩子
Mother.h
#import <Foundation/Foundation.h>#import "TestDelegate.h"@interface Mother : NSObject<TestDelegate>{ }@property(nonatomic)NSString* name;+(Mother*)initWithName:(NSString*)str;@end
很明顯 在這裡 mother這個類 接受了Testdelegate這個代理 注意使用某個代理的形式為 @interface Mother : NSObject<TestDelegate>
Mother.m
#import "Mother.h"@implementation Mother@synthesize name;+(Mother*)initWithName:(NSString *)str{ Mother* moth = [[Mother alloc]init]; moth.name = str; return moth;}-(void)feetBaby{ NSLog(@"開始喂孩子了");}@end
mother使用了TestDelegate這個代理 所以要實現feetbaby方法,前面說過@requird修飾的方法是必須實現的 要不會報錯,@optional修飾的可以選擇 實現不實現無所謂,下面看一下怎麼main函數的寫法
main.m
#import <Foundation/Foundation.h>#import "Baby.h"#import "Mother.h"int main(int argc, const char * argv[]) { @autoreleasepool { Baby*baby = [Baby initWithName:@"bob"]; Mother* mot = [Mother initWithName:@"Lily"]; baby.delegate = mot ; [baby hungry]; } return 0;}
一定要注意這裡 baby.delegate = mot ; 這句代碼,實現了baby的代理給了mot。