代理模式的使用场合
当一个类的某些功能需要被别人来实现,但是既不明确是些什么功能,又不明确谁来实现这些功能的时候,委托模式就可以派上用场。例如你可以再写个类,实现也是完全可以的。换谁来,只要它实现了这个方法,我就可以委托它来做这个事。说到底一切都是为了使类之间的耦合性更松散。好的代码应该对扩展开放,对修改关闭。
事例
1.委托者的.h文件中的代理指定以及声明
#
import <UIKit/UIKit.h>
#
import "LeftBarModel.h"
@protocol LeftBodyCellDelegate <NSObject>
/**
* @Description item选中跳转对应的控制器
* @param 被点击的按钮
*/
- (
void)selectedItemButton:(NSInteger)index;
@optional
- (
void)optionalFouction;
@end
@interface LeftBodyTableViewCell : UITableViewCell
@property(nonatomic,weak)id<LeftBodyCellDelegate> leftBodyCellDelegate;
@end
2.委托者的.m文件中调用代理中的方法
- (
void)itemButonClick:(
UIButton *)button
{
if (
self.leftBodyCellDelegate && [
self.leftBodyCellDelegate respondsToSelector:
@selector(selectedItemButton:)])
{
[
self.leftBodyCellDelegate selectedItemButton:button
.tag -
1000];
}
}
3.代理控制器中的代码
@interface RootViewController ()<UITableViewDelegate,UITableViewDataSource,LeftBodyCellDelegate>
cell
.leftBodyCellDelegate =
self;
4.实现协议中规定的方法了
#pragma mark --------------- LeftBodyCellDelegate
- (
void)selectedItemButton:(NSInteger)index
{
}
原文点这里
转载请注明原文地址: https://ju.6miu.com/read-671643.html