iOS设计模式之代理模式

简介:

代理模式

基本理解

  • 代理模式(Proxy),为其他对象提供一种代理以控制对这个对象的访问。

代理模式的应用

  • 远程代理:就是为一个对象在不同的地址空间提供据不代表。这样可以隐藏一个对象存在于不同地址空间的事实。
  • 虚拟代理:是根据需要创建开销很大的对象,通过它来存放实例化需要很长时间的真实对象。
  • 安全代理:用来控制真实对象访问时的权限。
    *智能指引:是指当调用真实的对象时,代理处理另外一些事。

例子

ChildViewCongroller.h

// // ChildViewController.h // DelegateDemo // // Created by zhanggui on 15/8/6. // Copyright (c) 2015年 zhanggui. All rights reserved. // #import <UIKit/UIKit.h> @protocol ChildDelegate <NSObject>

-(void)changeColor:(UIColor *)color;

@end @interface ChildViewController : UIViewController
{

}

@property(assign,nonatomic)id <ChildDelegate>ChildDelegate;

@end

ChildVIewController.m

// // ChildViewController.m // DelegateDemo // // Created by zhanggui on 15/8/6. // Copyright (c) 2015年 zhanggui. All rights reserved. // #import "ChildViewController.h" @interface ChildViewController () @end @implementation ChildViewController

- (void)viewDidLoad {
 [super viewDidLoad];
 self.view.backgroundColor = [UIColor whiteColor];
 UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 100, 200, 50)];
 [button addTarget:self action:@selector(show) forControlEvents:UIControlEventTouchUpInside];
// button.backgroundColor = [UIColor redColor];
 [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
 [button setTitle:@"返回调用代理" forState:UIControlStateNormal];
 [self.view addSubview:button];
}
-(void)show {
 [_ChildDelegate changeColor:[UIColor redColor]];
 [self.navigationController popToRootViewControllerAnimated:YES];
}
@end

在一个ViewController中去push出来ChildViewController。点击ChildViewController中的按钮改变根视图的背景色
ViewController.h

// // ViewController.h // DelegateDemo // // Created by zhanggui on 15/8/6. // Copyright (c) 2015年 zhanggui. All rights reserved. // #import <UIKit/UIKit.h> #import "ChildViewController.h" @interface ViewController : UIViewController<ChildDelegate>


- (IBAction)showChild:(id)sender;
@end

ViewController.m

// // ViewController.m // DelegateDemo // // Created by zhanggui on 15/8/6. // Copyright (c) 2015年 zhanggui. All rights reserved. // #import "ViewController.h" @interface ViewController () @end @implementation ViewController

- (void)viewDidLoad {
 [super viewDidLoad];
 
}
#pragma mark - ChildViewDelegate Mehtod
-(void)changeColor:(UIColor *)color {
 self.view.backgroundColor =color;
 NSLog(@"change color.....");
}
- (IBAction)showChild:(id)sender {
 ChildViewController *child = [ChildViewController new];
 child.ChildDelegate = self;
 [self.navigationController pushViewController:child animated:YES];

}
@end

这样通过代理就可以去实现。

相关文章
|
API iOS开发 设计模式
iOS 设计模式-外观模式
1.外观模式简介 外观模式(Facade)在开发过程中的运用频率非常高,尤其是在现阶段各种第三方SDK充斥在我们的周边,而这些SDK很大概率会使用外观模式。
1669 0
|
Android开发 iOS开发 生物认证
|
存储 数据安全/隐私保护 iOS开发
|
算法 iOS开发 测试技术
|
iOS开发 安全 设计模式
|
iOS开发 设计模式
iOS设计模式之原型模式
What is the 原型模式? 原型设计模式是通过一个原型拷贝的方式快速创建一个新的对象。 拷贝分为两种: 浅拷贝(同一个地址,不同的指针) 深拷贝(不同的地址,完全的独立) 二者区别在于是否生成新的一个地址 When using the 原型模型? 需要创建的对象应独立于其类型与创建方式。
882 0