zoukankan      html  css  js  c++  java
  • 使用@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

    细节

  • 相关阅读:
    ndt histogram_direction
    rplidar & hector slam without odometry
    点云的基本几何计算
    rplidar测试
    使用ZXing.Net生成与识别二维码(QR Code)
    C# 中使用 ThoughtWorks.QRCode.dll 生成指定尺寸和边框宽度的二维码
    .NET 二维码生成(ThoughtWorks.QRCode)
    zxing二维码的生成与解码(C#)
    netsh interface portproxy的一个简单例子
    Redis 客户端连接
  • 原文地址:https://www.cnblogs.com/YouXianMing/p/4521491.html
Copyright © 2011-2022 走看看