关于Object-C的协议和代理设计模式,gowhich在这里做了简单的小测试
代码文件列表:
main.m
Helloworld.h
Person.h
Person.m
代码如下:
main.m
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
|
#import <Foundation/Foundation.h> #import "Person.h" int main(int argc, const char * argv[]) {
@autoreleasepool { NSLog(@"Hello, World!"); Person *durban = [[Person alloc] init]; [durban requestGet]; [durban requestPost]; [durban requestPut]; } return 0; }
|
Helloworld.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
#import <Foundation/Foundation.h>
@protocol HelloWorld <NSObject>
@required -(void) requestPost; -(void) requestPut; @optional -(void) requestGet;
@end
|
Person.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
#import <Foundation/Foundation.h> #import "HelloWorld.h"
@interface Person : NSObject<HelloWorld>
-(void) getMethod;
@end
|
Person.m
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
|
#import "Person.h"
@implementation Person
-(void) getMethod { NSLog(@"获取数据的方法"); }
-(void) requestPost { NSLog(@"必须实现的方法:这是一个Post方法"); }
-(void) requestPut { NSLog(@"必须实现的方法:这是一个Put方法"); }
-(void) requestGet { NSLog(@"选择实现的方法:这是一个Get方法"); }
@end
|
gowhich得到的结果是:
1 2 3 4
| 2013-11-01 11:35:51.465 ProtocolTest[1989:303] Hello, World! 2013-11-01 11:35:51.467 ProtocolTest[1989:303] 选择实现的方法:这是一个Get方法 2013-11-01 11:35:51.467 ProtocolTest[1989:303] 必须实现的方法:这是一个Post方法 2013-11-01 11:35:51.468 ProtocolTest[1989:303] 必须实现的方法:这是一个Put方法
|