标签:
ios设计模式中的委托 Delegate
官方文档解释如下:
Delegation is a simple and powerful pattern in which one object in a program acts on behalf of, or in coordination with, another object. The delegating object keeps a reference to the other object—the delegate—and at the appropriate time sends a message to it. The message informs the delegate of an event that the delegating object is about to handle or has just handled. The delegate may respond to the message by updating the appearance or state of itself or other objects in the application, and in some cases it can return a value that affects how an impending event is handled. The main value of delegation is that it allows you to easily customize the behavior of several objects in one central object.
意译一下就是:代理是一种简单而功能强大的设计模式,这种模式用于一个对象“代表”另外一个对象和程序中其他的对象进行交互。 主对象(这里指的是delegating object)中维护一个代理(delegate)的引用并且在合适的时候向这个代理发送消息。这个消息通知“代理”主对象即将处理或是已经处理完了某一个事件。这个代理可以通过更新自己或是其它对象的UI界面或是其它状态来响应主对象所发送过来的这个事件的消息。或是在某些情况下能返回一个值来影响其它即将发生的事件该如何来处理。代理的主要价值是它可以让你容易的定制各种对象的行为。注意这里的代理是个名词,它本身是一个对象,这个对象是专门代表被代理对象来和程序中其他对象打交道的。
1 // ManDeleagte接口声明 2 @protocol ManDeleagte <NSObject> 3 -(void)onAgeChanged:(int)age; 4 @end 5 6 // ManListener实现 7 @interface ManListener : NSObject<ManDeleagte> 8 -(void)onAgeChanged:(int)age; 9 @end 10 11 // ManListener实现 12 @implementation ManListener 13 14 -(void)onAgeChanged:(int)age{ 15 NSLog(@"Age changed,Current age is %d",age); 16 } 17 @end
1 // 协议 相当于C++语言中的接口 2 @protocol IPeople <NSObject> 3 -(int)getAge; 4 -(NSString*)getName; 5 -(void)setAge:(int)age; 6 @end 7 8 // 类定义 并实现IPeople接口 多个接口用,相隔 9 @interface Man : NSObject<IPeople>{ 10 int _age; 11 } 12 -(id)init; 13 -(int)getAge; 14 -(NSString*)getName; 15 -(void)setAge:(int)age; 16 17 @property id<ManDeleagte> delegate; 18 19 @end 20 21 // 类实现 22 @implementation Man 23 -(int)getAge{ 24 return _age; 25 } 26 27 -(instancetype)init{ 28 self = [super init]; 29 if (self) { 30 self.delegate = nil; 31 _age = 20; 32 } 33 return self; 34 } 35 36 -(NSString*)getName{ 37 return @"jinpangpang"; 38 } 39 40 -(void)setAge:(int)age{ 41 // 通知给外界 42 if (age!=_age) { 43 if (self.delegate) { 44 [self.delegate onAgeChanged:age]; 45 } 46 } 47 _age = age; 48 } 49 @end
1 // 调用 2 int main(int argc, char * argv[]) { 3 Man *m = [[Man alloc] init]; 4 // 给对象指定一个delegate 5 [m setDelegate:[[ManListener alloc]init]]; 6 [m setAge:21]; 7 8 NSLog(@"%@",[m getName]); 9 NSLog(@"%d",[m getAge]); 10 @autoreleasepool { 11 return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class])); 12 } 13 }
// 运行结果 2015-11-28 17:33:23.825 L15Protcal[8740:991452] Age changed,Current age is 21 2015-11-28 17:33:23.826 L15Protcal[8740:991452] jinpangpang 2015-11-28 17:33:23.827 L15Protcal[8740:991452] 21
标签:
原文地址:http://www.cnblogs.com/-jpp/p/5003052.html