上一篇是對觀察者模式的概念上的討論掷邦,這一篇是利用通知來實現(xiàn)觀察者模式白胀,錯誤之處敬請批評指正。
代碼示例
在iOS中日常開發(fā)中抚岗,CocoaTouch框架的 通知 和 KVO 都實現(xiàn)了觀察者模式或杠。下面小江簡單用兩種模式實現(xiàn)下,具體通知和kvo的原理就不在此贅述了宣蔚,畢竟不是設計模式的重點~
通知實現(xiàn)
//直接寫了具體主題角色向抢,偷了懶沒有寫抽象主題
@interface Bell : NSObject
- (void)attachObserver:(Observer *)observer;
- (void)classBegin;
- (void)classEnd;
@property (nonatomic, strong) NSMutableArray *observers;
@end
@implementation Bell
- (void)attachObserver:(Observer *)observer {
//這里有點照本宣科了,其實ios的通知里并不需要這個方法胚委,這里只是想和類圖中的結構保持一致
[self.observers addObject:observer];
}
- (void)classBegin {
NSLog(@"上課鈴響了");
NSDictionary *dic = @{@"classBegin":@YES};
[[NSNotificationCenter defaultCenter] postNotificationName:@"classBellRing"
object:self userInfo:dic];
}
- (void)classEnd {
NSLog(@"下課鈴響了");
NSDictionary *dic = @{@"classBegin":@NO};
[[NSNotificationCenter defaultCenter] postNotificationName:@"classBellRing"
object:self userInfo:dic];
}
@end
//抽象觀察者角色
@interface Observer : NSObject
- (void)update:(NSNotification *)notification;
@end
@implementation Observer
- (id)init {
self = [super init];
if (self) {
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(update:) name:@"classBellRing" object:nil];
}
return self;
}
- (void)update:(NSNotification *)notification {
//to be Override...
}
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:@"classBellRing"];
}
@end
//具體觀察者角色
@interface Student : Observer
@end
@implementation Student
- (void)update:(NSNotification *)notification {
NSDictionary *userInfo = notification.userInfo;
if ([[userInfo objectForKey:@"classBegin"] boolValue]) {
[self classBegin];
} else {
[self classEnd];
}
}
- (void)classBegin {
NSLog(@"上課了挟鸠,學生回到教室");
}
- (void)classEnd {
NSLog(@"下課了,學生離開教室");
}
@end
//主函數(shù)調用
int main(int argc, const char * argv[]) {
@autoreleasepool {
//觀察者模式
Bell *bell = [[Bell alloc] init];
Student *stu1 = [[Student alloc] init];
[bell attachObserver:stu1];
[bell classBegin];
[bell classEnd];
}
return 0;
}
運行結果:
2017-01-06 23:37:49.022 DesignPattern[3309:91471] 上課鈴響了
2017-01-06 23:37:49.023 DesignPattern[3309:91471] 上課了亩冬,學生回到教室
2017-01-06 23:37:49.023 DesignPattern[3309:91471] 下課鈴響了
2017-01-06 23:37:49.023 DesignPattern[3309:91471] 下課了艘希,學生離開教室
Program ended with exit code: 0
以上,如有問題敬請批評指正~本文系作者原創(chuàng)硅急,轉載請注明出處