委托模式(代理模式)详解

什么是委托模式:

      委托delegate是协议的一种,通过一种@protocol的方式来实现。

委托模式的作用:

      我们首先要知道委托模式的作用到底有哪些?理清这个问题,才知道改在什么情况下去用这个delegate。

委托的作用有两个,一个是传值,另一个是传事件

  • 所谓传值就是B类要把自己的一个数据或者对象传给A类,让A类去展示或者处理。
  • 所谓的传事件就是,简单来说假如A类发生某个事件,它本身并不出来,而是通过委托delegate的形式,让它的委托对象B类去处理(委托对象B类就要实现委托中的方法)。

实现委托需要去注意的几点:

  • 需要定义协议@protocol,这个协议可以单独去newfile一个,也可以放在委托对象的头文件里(一般用这个方法)。
  • 在这个协议中定义委托对象需要委托别人处理的一些方法,用于传值或者传事件。
  • 委托类中要定义一个协议的实例对象,属性一般设置为assign(例如:@property (nonatomic,assign)id<MyDelegate> delegate;)
  • 被委托的类中需要在自己的interface中声明协议:<XXXDelegate>,表示该类要实现XXXDelegate协议中的方法。
  • 委托类对象的delegate设置为被委托对象,方法有两种:1.委托类对象.delegate = 被委托对象  2.在被委托类里定义一个委托对象,设置 委托对象.delegate = self.

接下来通过实例来解释两种方法:

1.委托传值

  • 委托类:Customer其中委托协议定义了一个方法,表示Customer要买一个手机,会传递一个手机型号参数,customer通过委托delegate调用这个方法表示customer要买手机。
  • 被委托类:Businessman,其继承这个协议,实现了这个协议中的方法,也即处理了委托类customer要买手机的需要。

Customer.h

@protocol MyDelegate <NSObject>  
  
-(void)buyIphone:(NSString*)iphoneType;  
  
@end  
  
@interface Customer : NSObject  
  
@property(nonatomic,assign)id<MyDelegate> delegate;  
  
-(void)willBuy;  
  
@end  

 Customer.m

@implementation Customer    
  
-(void)willBuy {  
    [delegate buyIphone:@"Iphone6S"];  
}  
  
@end  

 Businessman.h

@interface Businessman : NSObject<MyDelegate>  
  
@end  

 Businessman.m

@implementation Businessman  
  
-(void)buyIphone:(NSString *)iphoneType {  
    NSLog(@"There is an Iphone store,we have %@",iphoneType);  
}  
  
  
@end  

 main.m

int main(int argc, const char * argv[])  
{  
  
    @autoreleasepool {  
        
        Customer *customer = [[Customer alloc]init];          
        Businessman *businessman = [[Businessman alloc]init];  
        customer.delegate = businessman;  
        [customer willBuy];  
    }  
    return 0;  
}  

 2.委托传事件

委托类:Boss 他要处理起草文件和接电话的任务,但是他本身并不实现这些事件响应的方法,而是通过委托让他的被委托类来实现这些响应方法。

被委托类:Secretary 他受Boss的委托实现起草文件和接电话任务的方法。

Boss.h

@protocol MissionDelegate <NSObject>  
-(void)draftDocuments;  
-(void)tellPhone;  
@end  
@interface Boss : NSObject  
@property(nonatomic, assign)id<MissionDelegate> delegate;  
-(void)manage;  
@end  

 Boss.m

@implementation Boss  
-(void)manage {  
    [self.delegate draftDocuments];  
    [self.delegate tellPhone];  
}  
@end  

Secretary.h

@interface Secretary : NSObject <MissionDelegate>  
  
@end  

 Secretary.m

@implementation Secretary  
-(void)draftDocuments {  
    NSLog(@"Secretary draft documents");  
}  
-(void)tellPhone {  
    NSLog(@"Secretary tell phone");  
}  
@end  

 main.m

int main(int argc, const char * argv[])  
{  
    @autoreleasepool {       
        Boss *boss = [[Boss alloc] init];  
        Secretary *secretary =  [[Secretary alloc] init];  
        boss.delegate = secretary;  
        [boss manage];  
    }  
    return 0;  
}  

 

猜你喜欢

转载自1395014506.iteye.com/blog/2259961