iOS设计模式(01):观察者

来源:互联网 发布:淘宝电商账号什么意思 编辑:程序博客网 时间:2024/05/06 19:33

原文:http://beyondvincent.com/blog/2013/05/05/18/

iOS-Observer-PatterniOS-Observer-Pattern

什么是观察者模式

什么是观察者模式?你曾经订阅过报纸吗?在订阅报纸的时候,你不用去任何地方,只需要将你的个人地址信息以及订阅信息告诉出版社,出版社就知道如何将相关报纸传递给你。这种模式的第二个名称叫做发布/订阅模式

在GoF中是这样描述观察者模式的——观察者模式定义了一种一对多的依赖关系,让多个观察者对象同时监听某一个主题对象。这个主题对象在状态上发生变化时,会通知所有观察者对象,使它们能够自动更新自己。

观察者模式的的思想非常简单,Subject(主题)允许别的对象——观察者(这些对象实现了观察者接口)对这个Subject的改变进行订阅和取消订阅。当Subject发生了变化——那么Subject会将这个变化发送给所有的观察者,观察者就能对Subject的变化做出更新。在这里,Subject是报纸的出版社,而观察者则是订阅报纸的我和你,当Subject发生变化——有新的报纸,会做出通知——将报纸发送给所有的订阅者。

什么时候使用观察者模式?

  1. 当你需要将改变通知所有的对象时,而你又不知道这些对象的具体类型,此时就可以使用观察者模式。
  2. 改变发生在同一个对象中,并在别的地方需要将相关的状态进行更新。

iOS中观察者模式的实现方法

在iOS中观察者模式的实现有三种方法:

  1. Notification

Notification - NotificationCenter机制使用了操作系统的功能。通过NSNotificationCenter可以让对象之间进行进行通讯,这些对象相互间可以不认识。当你用一个并行的流来推送通知,或者刷新数据库,并希望在界面中能够看到时,这非常有用。

NotificationCenter发布消息的方法如下所示:

NSNotification  * broadcastMessage = [ NSNotification  notificationWithName: AnyNotification  object: Self ];NSNotificationCenter  * notificationCenter = [ NSNotificationCenter  defaultCenter];[NotificationCenter postNotification: broadCastMessage];

上面的代码中,创建了一个NSNotification类型的对象,并指定名称为”broadcastMessage”,然后通过notificationCenter来发布这个消息。

要订阅感兴趣的对象中的相关事件,可以按照如下方法进行:

NSNotificationCenter  * notificationCenter = [ NSNotificationCenter  defaultCenter];[NotificationCenter addObserver: Self  selector: @ selector (update:) name: AnyNotification  object: nil ];

如上代码所示:订阅了一个事件,并通过@selector指定了一个方法。

// 收到通知中心发来的通知-(void)update:(NSNotification *) notification{    if ([[notification name] isEqualToString:AnyNotification])        NSLog (@"成功收到通知中心发来的名为%@的通知", AnyNotification);}

下面是运行上面代码,在控制台输出的内容:

2013-05-05 23:43:15.570 ObserverPattern[1738:c07] 成功收到通知中心发来的名为broadcastMessage的通知
  1.  KVO

通过KVO,某个对象中的特定属性发生了改变,别的对象可以获得通知。苹果官方文档对KVO有了很好的解释:Key-Value Observing Programming Guide。下面两种方法都可以改变对象中属性的值:

kvoSubj.changeableProperty = @"新的一个值";[kvoSubj setValue:@"新的一个值" forKey:@"changeableProperty"];

上面这种值改变的灵活性可以让我们对键值进行观察。

下面是新建的一个类KVOSubject,这个类中有一个属性changeableProperty:

@interface KVOSubject : NSObject@property (nonatomic, strong) NSString *changeableProperty;@end@implementation KVOSubject@end

接着新建了另外一个类KVOObserver,通过该类可以监听changeableProperty属性值的改变。

@interface KVOObserver : NSObject@end@implementation KVOObserver-(void) observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{    NSLog(@"KVO:值发生了改变");}@end

如上代码所示,KVOObserver类只有一个方法observeValueForKeyPath。当changeableProperty属性值的改变时,这个方法会被调用。下面是测试的代码:

- (IBAction)btnKVOObservationTest:(id)sender {    KVOSubject *kvoSubj = [[KVOSubject alloc] init];    KVOObserver *kvoObserver = [[KVOObserver alloc] init];    [kvoSubj addObserver:kvoObserver forKeyPath:@"changeableProperty"                 options:NSKeyValueObservingOptionNew context:nil];    kvoSubj.changeableProperty = @"新的一个值";    [kvoSubj setValue:@"新的一个值" forKey:@"changeableProperty"];    [kvoSubj removeObserver:kvoObserver forKeyPath:@"changeableProperty"];}

执行上面的代码,可以看到控制台输出如下结果:

2013-05-05 23:10:20.789 ObserverPattern[1358:c07] KVO:值发生了改变2013-05-05 23:10:20.790 ObserverPattern[1358:c07] KVO:值发生了改变
  1. 标准方法

先来看看Gof中对观察者模式定义的结构图:

Observer-StructureObserver-Structure

标准方法的实现是这样的:Subject(主题)知道所有的观察者,但是不知道它们的类型。下面我们就从创建Subject和Observer(观察者)的协议(protocol)开始。

@protocol StandardObserver -(void) valueChanged:(NSString *)valueName newValue:(NSString *) newValue;@end@protocol StandardSubject -(void) addObserver:(id) observer;-(void) removeObserver:(id) observer;-(void) notifyObjects;@end

下面,我们来创建一个Subject的implementation (实现)

@interface StandardSubjectImplementation : NSObject {    @private NSString *_valueName;    @private NSString *_newValue;}@property (nonatomic, strong) NSMutableSet *observerCollection;-(void)changeValue:(NSString *)valueName andValue:(NSString *) newValue;@end@implementation StandardSubjectImplementation-(NSMutableSet *) observerCollection{    if (_observerCollection == nil)        _observerCollection = [[NSMutableSet alloc] init];    return _observerCollection;}-(void) addObserver:(id)observer{    [self.observerCollection addObject:observer];}-(void) removeObserver:(id)observer{    [self.observerCollection removeObject:observer];}-(void) notifyObjects{    for (id observer in self.observerCollection) {        [observer valueChanged: _valueName newValue:_newValue];    }}-(void)changeValue:(NSString *)valueName andValue:(NSString *) newValue{    _newValue = newValue;    _valueName = valueName;    [self notifyObjects];}@end

接下来是Observer的implementation (实现):

@interface SomeSubscriber : NSObject @end@implementation SomeSubscriber-(void) valueChanged:(NSString *)valueName newValue:(NSString *)newValue{    NSLog(@"SomeSubscriber输出: 值 %@ 已变为 %@", valueName, newValue);}@end@interface OtherSubscriber : NSObject @end@implementation OtherSubscriber-(void) valueChanged:(NSString *)valueName newValue:(NSString *)newValue{    NSLog(@"OtherSubscriber输出: 值 %@ 已变为 %@", valueName, newValue);}@end

下面是演示的代码:

StandardSubjectImplementation * subj = [[StandardSubjectImplementation alloc] init];SomeSubscriber * someSubscriber = [[SomeSubscriber alloc] init];OtherSubscriber * otherSubscriber = [[OtherSubscriber alloc] init];[Subj addObserver: someSubscriber];[Subj addObserver: otherSubscriber];[subj changeValue:@"version" andValue:@"1.0.0"];

上面代码运行的log如下所示:

2013-05-05 23:19:04.662 ObserverPattern[1459:c07] OtherSubscriber输出: 值 version 已变为 1.0.02013-05-05 23:19:04.664 ObserverPattern[1459:c07] SomeSubscriber输出: 值 version 已变为 1.0.0

代码实例

本文涉及到的相关实例代码和PDF归档可以到点击下图下载:

代码下载代码下载            pdf-iconpdf-icon

 

美文推荐:When to use Delegation, Notification, or Observation in iOS

_________________

本文由破船原创
转载请注明出处:BeyondVincent的博客

0 0
原创粉丝点击