zoukankan      html  css  js  c++  java
  • 委托模式-简单

    委托模式(代理模式):它是对一个类的功能进行扩展和复用的方法。当有两个对象参与处理同一个请求,接受请求的对象将请求委托给另一个对象来处理。

      比如: 你想送一个东西给你一个朋友 ,然后你的邻居正好要去你朋友那里 , 然后你委托他帮你送东西。

          这个时候就需要2个类 , 一个你自己 , 一个你的邻居。

         并且需要一份协议,  你和你的邻居需要遵守这份协议才能帮你送东西 , 否则就不能送。

      代码如下:

     

    Student.h

    #import <Foundation/Foundation.h>
    #import "friend.h"
    #import "Frien.h"
    @interface Student : NSObject<friend>
    @property(strong,nonatomic)Frien *frien;
    -(instancetype)initWithfrien:(Frien *)frien;
    @end
    

     Student.m

    #import "Student.h"
    
    @implementation Student
    - (instancetype)initWithfrien:(Frien *)frien
    {
        self = [super init];
        if (self) {
            _frien=frien;
        }
        return self;
    }
    -(void)songdongxi
    {
        [_frien songdongxi];
    }
    
    @end
    

     Frien.h

    #import <Foundation/Foundation.h>
    #import "friend.h"
    
    @interface Frien : NSObject<friend>
    
    @end
    

     Frien.m

    #import "Frien.h"
    
    @implementation Frien
    
    
    -(void)songdongxi
    {
        NSLog(@"朋友送东西");
    }
    @end
    

     main.m

    #import <Foundation/Foundation.h>
    #import "Student.h"
    #import "Frien.h"
    int main(int argc, const char * argv[]) {
        @autoreleasepool {
            Frien *f=[Frien new];
            Student *stu=[[Student alloc] initWithfrien:f];
            if ([stu conformsToProtocol:@protocol(friend) ]) {
                if ([stu respondsToSelector:@selector(songdongxi)]) {
                    [stu songdongxi];
                }
            }  else{
                NSLog(@"不送");
            }
            
            
            
            
            
            
            
            
        }
        return 0;
    }
    
  • 相关阅读:
    操作系统——第四章 文件管理
    操作系统——第三章 内存管理
    操作系统——第二章 进程管理
    last-child到底怎么用
    Https个人总结
    白话https
    RSA算法
    算法导论笔记:11散列表(哈希表)
    算法导论笔记:10基本数据结构(番外)
    算法导论笔记:09中位数和顺序统计量
  • 原文地址:https://www.cnblogs.com/fume/p/5245320.html
Copyright © 2011-2022 走看看