• 使用@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

    细节

  • 相关阅读:
    commons
    Dozer数据对象转换神器
    xstream
    javassist
    JAVA设计模式之单例模式
    单例模式
    OC_自动引用计数器_0x04
    OC_自动引用计数器_0x03
    OC_自动引用计数器_0x02
    OC_自动引用计数器_0x01
  • 原文地址:https://www.cnblogs.com/YouXianMing/p/4521491.html
Copyright © 2020-2023  润新知