zoukankan      html  css  js  c++  java
  • OC-Protocol实现业务代理

    创建一个Protocol,相当于java的接口,但,有些方法不必实现,例如以下

    #import <Foundation/Foundation.h>
    
    @protocol MyProtocol
    
    @optional
    - (void) test1;
    
    - (void) test2;
    
    - (void) test3;
    @required
    - (void) test4;
    
    @end

    继承了该协议,并声明在@optional下的代码方法不是必须实现的,但@required下的方法必须实现。

    例如以下Book类

    #import <Foundation/Foundation.h>
    #import "MyProtocol.h"
    
    @interface Book : NSObject <MyProtocol>
    
    @property (nonatomic,assign) int price;
    
    @end

    #import "Book.h"
    
    @implementation Book
    
    - (void) test4
    {
    }
    
    - (void) dealloc
    {
        NSLog(@"Book is dealloc");
        [super dealloc];
    }
    
    @end

    创建一个模拟买票样例。仅仅要实现了该接口 就可以作为买票代理人

    #import <Foundation/Foundation.h>
    
    @protocol TicketAgentProtocol <NSObject>
    
    - (int) getTicketCount;
    
    - (int) getTicketPrice;
    
    
    @end

    #import <Foundation/Foundation.h>
    
    #import "TicketAgentProtocol.h"
    
    @interface Person : NSObject
    
    @property (nonatomic,retain) id<TicketAgentProtocol> delegate;
    
    - (NSString *) buyTicket;
    
    @end


    #import "Person.h"
    
    @implementation Person
    
    - (NSString *) buyTicket
    {
        return [NSString stringWithFormat:@"TICKET COUNT:%d ,TICKET PRICE:%d",
                [_delegate getTicketCount],[_delegate getTicketPrice]];
    }
    
    -(void)dealloc
    {
        [_delegate release];
        
        [super dealloc];
    }
    
    @end

    创建一个符合条件的“代理人”,就可以实现买票业务。

    #import <Foundation/Foundation.h>
    #import "TicketAgentProtocol.h"
    
    @interface Other : NSObject <TicketAgentProtocol>
    
    @end

    #import "Other.h"
    
    @implementation Other
    
    - (int) getTicketCount
    {
        return 1000;
    }
    
    - (int) getTicketPrice
    {
        return 100;
    }
    
    @end

    #import <Foundation/Foundation.h>
    #import "TicketAgentProtocol.h"
    #import "Person.h"
    #import "Other.h"
    
    int main(int argc, const char * argv[])
    {
    
        @autoreleasepool {
            
            Person *p=[[[Person alloc] init] autorelease];
            Other *other=[[[Other alloc] init] autorelease];
            p.delegate=other;
            
            NSLog(@"%@",[p buyTicket]);
            
        }
        return 0;
    }


  • 相关阅读:
    python+selenium之中类/函数/模块的简单介绍和方法调用
    python之类
    Python+Selenium之断言对应的元素是否获取以及基础知识回顾
    Python+Selenium之摘取网页上全部邮箱
    C# 事件
    IConfigurationSectionHandler 接口
    ReaderWriterLockSlim 类
    log4net 按照日期备份日志
    Redis .net 客户端 分布式锁
    SQL Server Compact/SQLite Toolbox
  • 原文地址:https://www.cnblogs.com/zfyouxi/p/5091956.html
Copyright © 2011-2022 走看看