IOS开发中的委托模式

来源:互联网 发布:mac qq接受文件没反应 编辑:程序博客网 时间:2024/06/05 15:56

委托模式:
将所需要实现的具体方法交给某个委托对象,协议类似接口,只定义方法名,没有具体方法实现。因此委托这种设计模式在cocoa框架里面跟协议是有密切关系的。

  • 使用委托模式的目的:
    为了降低类与类之间代码的耦合度,我们使用协议来帮助实现某个类的功能。常用于类的封装,类与类之间相互调用。
  • 具体要求与实现:
    1.要求:
    在两个互相独立的类中,类A(继承于UIButton)点击btn时,类B必须响应3个打印方法。
    2.关键代码的实现:
    定义协议P,里面只定义方法名,具体实现看委托对象的具体动作。
    —–2.1在委托者A判断委托对象B是否有实现其协议里面的方法,并且判断其动作是否符合规定。
    代码为:

    if([self.delegate respondsToSelector:@selector(printName)]){        NSLog(@"给委托者...") ;        [self.delegate printName] ;    }

    —–2.2 在委托者A定义一个协议的属性delegate,并设置其委托对象B…
    代码为:

    - (void)viewDidLoad{    [super viewDidLoad] ;    YANbtn *btn = [[YANbtn alloc]init] ;    btn.delegate = self ;    [self.view addSubview:btn] ;}

    —–2.3在委托对象B中实现相应的协议方法:
    代码为 :

        #pragma btnProtocol-(void)printName{    self.label.text = @"实现委托" ;    [self.label setTextColor:[UIColor redColor]] ;}
    三个类的结构图和关系如下:

    这里写图片描述
    委托对象B代码:

    #import "DesignModeViewController.h"#import "YANbtn.h"@interface DesignModeViewController ()<btnProtocol>@property (weak, nonatomic) IBOutlet UILabel *label;@end@implementation DesignModeViewController- (void)viewDidLoad{    [super viewDidLoad] ;    YANbtn *btn = [[YANbtn alloc]init] ;    btn.delegate = self ;    [self.view addSubview:btn] ;}#pragma btnProtocol(void)printName{    self.label.text = @"实现委托" ;    [self.label setTextColor:[UIColor redColor]] ;}@end

    委托者A的代码:

    #import "YANbtn.h"@implementation YANbtn- (id)initWithFrame:(CGRect)frame{    self = [super initWithFrame:frame];    if (self) {        self.backgroundColor = [UIColor orangeColor] ;        [self setTitle:@"YANbtn" forState:UIControlStateNormal ];        self.frame = CGRectMake(30, 400, 100, 30) ;        [self setFont:[UIFont systemFontOfSize:11]] ;        [self addTarget:self action:@selector(btnAction) forControlEvents:UIControlEventTouchUpInside] ;    }    return self;}-(void)btnAction{    if([self.delegate respondsToSelector:@selector(printName)]){        NSLog(@"给委托者...") ;        [self.delegate printName] ;    }}@end

    协议P的代码:

    #import <Foundation/Foundation.h>@protocol btnProtocol <NSObject>@optional-(void)printName ;-(void)printAge ;@end
0 0
原创粉丝点击