ios学习笔记(二)--代理设计模式

来源:互联网 发布:php空间免费 编辑:程序博客网 时间:2024/06/06 04:55

我使用这种设计模式,写了一个宠物购物的示例


接口:

#import <Foundation/Foundation.h>@protocol PetInterface <NSObject>    @required    -(void)PetKind; //什么种类的pet    -(void)PetColor;  //pet的颜色    @optional    -(NSString *)getName;//取得宠物名称@end

Husky:

/*   Husky.h */#import <Foundation/Foundation.h>#import "PetInterface.h"@interface Husky : NSObject <PetInterface>@end/*    Husky.m   */#import "Husky.h"@implementation Husky<span></span>//实现协议-(void)PetKind{    NSLog(@"Cute Husky...");}-(void)PetColor{    NSLog(@"White and Brown...");}-(NSString *)getName{    return @"Husky";}@end


柴犬:

/*  chaiq.h  */#import <Foundation/Foundation.h>#import "PetInterface.h"@interface Chaiq : NSObject<PetInterface>@end /*  chaiq.m  */#import "Chaiq.h"@implementation Chaiq-(void)PetKind{    NSLog(@"Cute ChaiQuan...");}-(void)PetColor{    NSLog(@"Big YELLOW...");}-(NSString *)getName{    return @"ChaiQuan";}@end


宠物代理商的代码:

/* delegate.h  */#import <Foundation/Foundation.h>#include "PetInterface.h"@interface PetDelegate : NSObject <PetInterface>{    id<PetInterface> c;}-(void)salePet;    -(instancetype)initWithPet:(id<PetInterface>)v;@end/*  delegate.m  */#import "PetDelegate.h"@implementation PetDelegate    -(instancetype)initWithPet:(id<PetInterface>)v{        self = [super init];        if (self) {            self->c = v;        }        return self;    }    -(void)PetColor{        [self->c PetColor];    }    -(void)PetKind{        [self->c PetKind];    }    -(void)salePet{        NSString *str = [self->c getName];        NSLog(@"Sale %@",str);    }    @end

实现一个购买宠物的过程

#import <Foundation/Foundation.h>#import "PetInterface.h"#import "PetDelegate.h"#import "Husky.h"#import "Chaiq.h"int main(int argc, const char * argv[]) {    @autoreleasepool {        Husky *husky = [[Husky alloc]init];        Chaiq *chaiq = [[Chaiq alloc]init];        PetDelegate *delegate1 = [[PetDelegate alloc]initWithPet:husky];        PetDelegate *delegate2 = [[PetDelegate alloc]initWithPet:chaiq];                [delegate1 PetKind];  //代理商向你介绍宠物的种类        [delegate1 PetColor];<span></span>//向你介绍宠物的颜色        [delegate1 salePet];<span></span>//决定购买                [delegate2 PetKind];        [delegate2 PetColor];        [delegate2 salePet];    }    return 0;}

总结:

新技能get


0 0