- 代理模式:为其他对象创建一个代理以控制对这个对象的访问
- UML解释:客户端向Proxy发起一个Request()请求,Proxy对象会把这个Request转发给Proxy对象的RealSubject。RealSubject会实施操作间接满足Subject要求。举一个生活中的例子就比较好理解了——去饭店点餐,我们就是UML中的Subject(客户端)、Proxy就是饭店的服务员、RealSubject就是厨师。我们不能直接向厨师点餐,我们把点餐(Request())请求发送给服务员(Proxy)。Proxy(服务员)将菜单转发给厨师(RealSubject)。其实为你服务的还是厨师。
- 例如 :Button类有两个子类ButtonA、ButtonB,我们通过对Button提供一个抽象工厂方法来产生不同的button子类:
- 应用场景:
- 为位于不同地址空间或网络的对象提供本地代表 ——远程代理(不知道VPN代理是不是就是这么实现的)
- 根据要求创建重型的对象 ——虚拟代理
- 根据不同访问权限控制对原对象的访问 ——保护代理(例如VIP特权,代理会根据权限分流数据)
- Cocoa Touch中的代理模式:
1 - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 2 { 3 return self.cityListArrary.count; 4 } 5 6 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 7 { 8 static NSString *cellID = @"cityListCell"; 9 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID]; 10 if (cell == nil) { 11 cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID]; 12 } 13 //cell.selectionStyle = UITableViewCellSelectionStyleNone; 14 //cell.textLabel.text = _cityListArrary[indexPath.row]; 15 cell.selectionStyle = UITableViewCellSelectionStyleNone; 16 cell.textLabel.text = [[_cityListArrary objectAtIndex:indexPath.row] objectForKey:@"name"]; 17 cell.textLabel.font = [UIFont systemFontOfSize:FontSizeScaleWith6Plus(VICE_TITLE_FONT_SIZE)]; 18 cell.textLabel.textColor = UIColorFromRGB(0x999999); 19 return cell; 20 } 21 22 //------------------------------------------------------------------------------------------ 23 #pragma mark -Delegate 24 -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 25 { 26 if ([self.distinguish isEqualToString:@"freeFarm"]) 27 { 28 if ([self.delegate respondsToSelector:@selector(sendCountyName:andCountyId:)]) 29 { 30 NSString * countyName = [[_cityListArrary objectAtIndex:indexPath.row] objectForKey:@"name"]; 31 //NSString * cityName = [[_dataFirst objectAtIndex:indexPath.row] objectForKey:@"name"]; 32 NSInteger county_id = [[[_cityListArrary objectAtIndex:indexPath.row] objectForKey:@"county_id"] intValue]; 33 [self.delegate sendCountyName:countyName andCountyId:county_id]; 34 [self.navigationController popViewControllerAnimated:YES]; 35 } 36 37 } 38 else 39 { 40 LVLandShowViewController *landShowViewController = [[LVLandShowViewController alloc]init]; 41 [self.navigationController pushViewController:landShowViewController animated:NO]; 42 } 43 44 }
/** 我想大家对UITableView的代理一定太熟悉了,那我们就分析一下系统这种代理模式:其中UITableView就是委托人(Subject),因为UITableView具体要长成什么样子它自己并不知道。那么就要找一个代理人来为我服务告诉我所需要的所有材料(ViewController)。为什么ViewController可以是我的代理人,那是必须的,ViewController你有所有我想知道的数据你就要成为我的代理。但是ViewController想要成为我的代理人它必须要有一定资质(UITableViewDelegate、UITableViewDataSource)。一旦ViewController有了资质就可以成为我的代理了。最后就是代理人该以什么方式什么规则告诉我需要的数据。没错协议。因为委托人声明了协议,那我代理人就可以用协议中指定的规则来为委托人服务 */
- 总结:代理模式在Cocoa Touch中很常见一定要灵活运用。这里只是介绍了一个很基本的例子如果后期有更好的例子会补充。