您的位置:首页 > 移动开发 > IOS开发

IOS 那些设计模式,持续更新中...

2016-08-31 15:53 477 查看
引言


IOS中的设计模式,也就那么几种。对于初学者来说,确实感到有点晕乎,但是我们可以一个一个的击破。就不会感到那么难懂晕乎了。而且当我们真正熟悉并且熟练使用这些设计模式之后,你会发现我的代码变的好清晰啊,看你代码的人也会觉得,窝草!你好叼啊。好了,就不发鸡汤了。下面直接给干活。

第一种:代理模式(delegate)


代理是一种很常见的设计模式,苹果的好多框架里面都使用这种模式。尤其对于使用tableview的人来说,再熟悉不过了。就以顾客到中介买房子为例。

一、创建delegate(就是中介公司)
//.h部分
@protocol HousingIntermediaryDelegate <NSObject>
@required
// 买多大的房子
- (void)howMuchOfHouse:(NSInteger)suqre;
@optional
// 买哪里的
- (void)whatPlace:(NSString *)plcae;
@end
@interface HousingIntermediary : NSObject
@property (nonatomic,weak) id<HousingIntermediaryDelegate>delegate;

- (void)buyHouseWithSqare:(NSInteger)sqare;
- (void)buyHouseWithPlace:(NSString *)plcae;
@end

//.m实现部分
@implementation HousingIntermediary

- (void)buyHouseWithSqare:(NSInteger)sqare {
if (self.delegate && [self.delegate respondsToSelector:@selector(howMuchOfHouse:)]) {
[self.delegate howMuchOfHouse:sqare];
}
}

- (void)buyHouseWithPlace:(NSString *)plcae {
if (self.delegate && [self.delegate respondsToSelector:@selector(whatPlace:)]) {
[self.delegate whatPlace:plcae];
}
}
@end

二、验证代理方法
// 在viewController 类中进行调用
- (void)viewDidLoad {
[super viewDidLoad];
HousingIntermediary *house = [[HousingIntermediary alloc] init];
house.delegate = self;
[house buyHouseWithSqare:110];
[house buyHouseWithPlace:@"南京市江宁区"];
}
// HousingIntermediaryDelegate 方法
#pragma mark -- HousingIntermediaryDelegate

- (void)howMuchOfHouse:(NSInteger)suqre {
NSLog(@"您想买多大的房子:%ld平",suqre);
}

- (void)whatPlace:(NSString *)where {
NSLog(@"您想买哪边的房子:%@XX小区",where);
}

// 打印的结果
2016-09-01 10:07:35.054 Block[883:261799] 您想买多大的房子:110平
2016-09-01 10:07:35.068 Block[883:261799] 您想买哪边的房子:南京市江宁区XX小区


持续更新中…
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ios 设计模式 delegate