定义
代理模式(Proxy),为其他对象提供一种代理以控制对这个对象的访问.
使用场景
1.远程代理,也就是为一个对象在不同的地址空间提供局部代表.这样可以隐藏一个对象存在于不同地址空间的事实.
2.虚拟代理,是根据需要创建开销很大的对象.通过它来存放实例化需要很长时间的真实对象.
3.安全代理,用来控制真实对象访问的权限.
4.智能指引,是指当调用真实的对象时,代理处理另外一些事.
实现代码
// SchoolGirl.h
#import <Foundation/Foundation.h>
@interface SchoolGirl : NSObject
@property (nonatomic, copy) NSString *name;
@end
// SchoolGirl.m
#import "SchoolGirl.h"
@implementation SchoolGirl
@end
// Pursuit.h
#import "GiveGift.h"
@class SchoolGirl;
@interface Pursuit : GiveGift
@property (nonatomic, copy) SchoolGirl *girl;
@end
// Pursuit.m
#import "Pursuit.h"
#import "SchoolGirl.h"
@implementation Pursuit
-(void)giveDolls:(SchoolGirl *)schoolGirl
{
NSLog(@"%@送你洋娃娃",schoolGirl.name);
}
-(void)giveFlowers:(SchoolGirl *)schoolGirl
{
NSLog(@"%@送你花",schoolGirl.name);
}
-(void)giveChocolate:(SchoolGirl *)schoolGirl
{
NSLog(@"%@送你巧克力",schoolGirl.name);
}
@end
// GiveGift.h
#import <Foundation/Foundation.h>
@class SchoolGirl;
@interface GiveGift : NSObject
-(void)giveDolls:(SchoolGirl *)schoolGirl;
-(void)giveFlowers:(SchoolGirl *)schoolGirl;
-(void)giveChocolate:(SchoolGirl *)schoolGirl;
@end
// GiveGift.m
#import "GiveGift.h"
@implementation GiveGift
@end
// Proxy.h
#import "GiveGift.h"
@class Pursuit;
@interface Proxy : GiveGift
@property (nonatomic, copy) Pursuit *pursuit;
@end
// Proxy.m
#import "Proxy.h"
#import "Pursuit.h"
#import "SchoolGirl.h"
@implementation Proxy
-(void)giveDolls:(SchoolGirl *)schoolGirl
{
Pursuit *pursuit = [[Pursuit alloc] init];
[pursuit giveDolls:schoolGirl];
}
-(void)giveFlowers:(SchoolGirl *)schoolGirl
{
Pursuit *pursuit = [[Pursuit alloc] init];
[pursuit giveFlowers:schoolGirl];
}
-(void)giveChocolate:(SchoolGirl *)schoolGirl
{
Pursuit *pursuit = [[Pursuit alloc] init];
[pursuit giveChocolate:schoolGirl];
}
@end
// main.m
// 代理模式(Proxy),为其他对象提供一种代理以控制对这个对象的访问.
#import <Foundation/Foundation.h>
#import "SchoolGirl.h"
#import "Proxy.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
SchoolGirl *jiaojiao = [[SchoolGirl alloc] init];
jiaojiao.name = @"jiaojiao";
Proxy *proxy = [[Proxy alloc] init];
[proxy giveDolls:jiaojiao];
[proxy giveFlowers:jiaojiao];
[proxy giveChocolate:jiaojiao];
}
return 0;
}