使用@selector模仿代理功能降低代码耦合度

使用@selector模仿代理功能降低代码耦合度

使用@selector模仿代理功能降低代码耦合度

 

说明

该模式的好处就是两个产生联系的对象间并没有具体的耦合代码,增删改查均很直观

 

源码

Model

//
//  Model.h
//  SELMethod
//
//  Created by YouXianMing on 15/5/22.
//  Copyright (c) 2015年 YouXianMing. All rights reserved.
//

#import <Foundation/Foundation.h>


#define SafePerformSelector(Stuff) \
do { \
_Pragma("clang diagnostic push") \
_Pragma("clang diagnostic ignored \"-Warc-performSelector-leaks\"") \
Stuff; \
_Pragma("clang diagnostic pop") \
} while (0)


@interface Model : NSObject


/**
 *  属性名字
 */
@property (nonatomic, strong)  NSString  *name;


/**
 *  设置代理与方法
 */
@property (nonatomic, weak) id    delegate;
@property (nonatomic)       SEL   method;


- (void)doSomeThing;


@end


//
//  Model.m
//  SELMethod
//
//  Created by YouXianMing on 15/5/22.
//  Copyright (c) 2015年 YouXianMing. All rights reserved.
//

#import "Model.h"

@implementation Model

- (void)doSomeThing {
    
    // 执行代理以及方法
    if (_method && _delegate) {
        SafePerformSelector([_delegate performSelector:_method withObject:self]);
    }
}

@end

ViewController
//
//  ViewController.m
//  SELMethod
//
//  Created by YouXianMing on 15/5/22.
//  Copyright (c) 2015年 YouXianMing. All rights reserved.
//

#import "ViewController.h"
#import "Model.h"

@interface ViewController ()

@property (nonatomic, strong) Model *model;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    // 初始化对象
    self.model        = [Model new];
    self.model.name   = @"YouXianMing";
    
    // 设置代理与方法
    self.model.method   = @selector(modelValue:);
    self.model.delegate = self;
    
    // 执行操作
    [self.model doSomeThing];
}

- (void)modelValue:(Model *)value {
    NSLog(@"%@", value.name);
}

@end

细节

使用@selector模仿代理功能降低代码耦合度

使用@selector模仿代理功能降低代码耦合度

上一篇:链表的常见操作


下一篇:Apache Hadoop 2.7如何支持读写OSS