设计模式之观察者模式

观察者模式(有时又被称为模型(Model)-视图(View)模式、源-收听者(Listener)模式或从属者模式)是软件设计模式的一种。在此种模式中,一个目标物件管理所有相依于它的观察者物件,并且在它本身的状态改变时主动发出通知。这通常透过呼叫各观察者所提供的方法来实现。此种模式通常被用来实现事件处理系统。
观察者模式是一种对象行为模式。它定义对象间的一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都得到通知并被自动更新。
例如下面这张图:

观察者.jpg

在这个图中,书刊发行中心会发布不同的书刊,用户会订阅这些书刊,当这些书刊有新的发布的时候,就会通知到用户。
这个“发行-订阅”模式就是一种的观察者模式,“书刊发行中心”就相当于观察者中的“通知中心”,当有新的期刊发行的时候,就会通知到各个观察者,然后观察者根据传递过来的信息来执行相应的业务。当书刊结束发行的时候,相应的也要移除对应的观察者
接下来我们就设计一下这个通知中心,根据分析我们可以看出,这个发行中心需要有增删订阅号的功能。每个书刊都会对应多个订阅者,同时,也需要有增删订阅者的功能。
根据面向协议编程的思想,我们定义下面这个协议:

#import <Foundation/Foundation.h>
#import "SubscriberProtocol.h"

NS_ASSUME_NONNULL_BEGIN

@protocol SubscriptionServiceProtocol <NSObject>

//添加订阅号
- (void)createSubscriptionNumber:(NSString *)subscriptionNumber;

//移除订阅号
- (void)removeSubscriptionNumber:(NSString *)subscriptionNumber;

//添加(某个标识)订阅者
- (void)addSubscriber:(id<SubscriberProtocol>)subscriber withSubscription:(NSString *)subscriptionNumber;

//移除(某个标识 )订阅者
- (void)removeSubscriber:(id<SubscriberProtocol>)subscriber withSubscription:(NSString *)subscriptionNumber;

//向某个订阅号发出信息
- (void)sendMessage:(id)message toSubscriptionNumber:(NSString *)subscriptionNumber;

@end

NS_ASSUME_NONNULL_END

任何遵守这个协议的类都可以是一个通知中心

当有新的书刊发行的时候,我们需要通过一定的渠道去通知到订阅者,因此我们这里定义了一个SubscriberProtocol协议,任何订阅者都必须遵守这个协议,才能够收到最新的书刊信息

#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN
//订阅者需遵守的协议
@protocol SubscriberProtocol <NSObject>

//收到被订阅者发来的信息
- (void)didReceiveSubscriptionMessage:(id)message withSubscriptionNumber:(NSString *)subscriptionNumber;

@end

NS_ASSUME_NONNULL_END

至此,我们的接口设计完成,接下来我们去实现以下这两个协议。
首先我们创建一个“书刊中心”类,这里我们使用单例(实际应用中根据自己需求去设计为单例或者普通的类)

#import <Foundation/Foundation.h>
#import "SubscriptionServiceProtocol.h"

NS_ASSUME_NONNULL_BEGIN

@interface SubscriptionServiceCenter : NSObject<SubscriptionServiceProtocol>

+ (instancetype)sharedService;

@end

NS_ASSUME_NONNULL_END
#import "SubscriptionServiceCenter.h"

@interface SubscriptionServiceCenter ()

//订阅中心的一些服务,key:服务名称  value:对应的订阅者列表
@property (strong, nonatomic) NSMutableDictionary<NSString *, NSHashTable *> *services;

@end

@implementation SubscriptionServiceCenter

+ (instancetype)sharedService {
    static SubscriptionServiceCenter *center = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        center = [[SubscriptionServiceCenter alloc] init];
    });
    return center;
}

- (instancetype)init {
    if (self = [super init]) {
        _services = [NSMutableDictionary dictionary];
    }
    return self;
}

#pragma mark - ------------ SubscriptionServiceProtocol ------------ Methods
- (void)createSubscriptionNumber:(nonnull NSString *)subscriptionNumber {
    //判断传入的标识是否为空
    if (!subscriptionNumber.length) return;
    
    //判断是否已经存在该订阅号
    if ([_services objectForKey:subscriptionNumber]) return;
    
    //创建hashTable,用来存储订阅者
    NSHashTable *hashTable = [NSHashTable weakObjectsHashTable];
    [_services setValue:hashTable forKey:subscriptionNumber];
}

- (void)removeSubscriptionNumber:(nonnull NSString *)subscriptionNumber {
    [_services removeObjectForKey:subscriptionNumber];
}

- (void)addSubscriber:(nonnull id)subscriber withSubscription:(nonnull NSString *)subscriptionNumber {
    //判断传入的订阅者和订阅号是否为空
    if (subscriber == nil || !subscriptionNumber.length) return;
    
    //取出已创建好的hashTable
    NSHashTable *hashTable = [_services objectForKey:subscriptionNumber];
    [hashTable addObject:subscriber];
}

- (void)removeSubscriber:(nonnull id)subscriber withSubscription:(nonnull NSString *)subscriptionNumber {
    //判断传入的订阅者和订阅号是否为空
    if (subscriber == nil || !subscriptionNumber.length) return;
    
    //取出已创建好的hashTable
    NSHashTable *hashTable = [_services objectForKey:subscriptionNumber];
    [hashTable removeObject:subscriber];
}

- (void)sendMessage:(id)message toSubscriptionNumber:(NSString *)subscriptionNumber {
    //判断订阅号是否为空
    if (!subscriptionNumber.length) return;
    
    //取出hashTable
    NSHashTable *hashTable = [_services objectForKey:subscriptionNumber];
    //遍历订阅者发出通知
    NSEnumerator *enumerator = [hashTable objectEnumerator];
    id<SubscriberProtocol> subscriber = nil;
    while (subscriber = [enumerator nextObject]) {
        if ([subscriber respondsToSelector:@selector(didReceiveSubscriptionMessage:withSubscriptionNumber:)]) {
            [subscriber didReceiveSubscriptionMessage:message withSubscriptionNumber:subscriptionNumber];
        }
    }
    
}

@end

这里我使用的是NSHashTable而不是NSMutableArray,因为NSHashTable会对传入的对象进行弱引用,当添加进来的对象,在外部的强引用消失以后,会自动释放,就不需要我们手动去移除
接下来我们创建两个观察者类

#import <Foundation/Foundation.h>
#import "SubscriberProtocol.h"

NS_ASSUME_NONNULL_BEGIN

@interface SubscriberA : NSObject<SubscriberProtocol>

@end

NS_ASSUME_NONNULL_END

#import "SubscriberA.h"

@implementation SubscriberA

#pragma mark - ------------ SubscriberProtocol ------------ Methods
- (void)didReceiveSubscriptionMessage:(id)message withSubscriptionNumber:(NSString *)subscriptionNumber {
    NSLog(@"%@ -- Message:%@ -- subscriptionNumber:%@", self, message, subscriptionNumber);
}

@end
#import <Foundation/Foundation.h>
#import "SubscriberProtocol.h"

NS_ASSUME_NONNULL_BEGIN

@interface SubscriberB : NSObject<SubscriberProtocol>

@end

NS_ASSUME_NONNULL_END

#import "SubscriberB.h"

@implementation SubscriberB

#pragma mark - ------------ SubscriberProtocol ------------ Methods
- (void)didReceiveSubscriptionMessage:(id)message withSubscriptionNumber:(NSString *)subscriptionNumber {
    NSLog(@"%@ -- Message:%@ -- subscriptionNumber:%@", self, message, subscriptionNumber);
}

@end

至此订阅中心和观察者都创建好了,接下来让我们赶紧使用一下吧

#import "ViewController.h"
#import "SubscriptionServiceCenter.h"
#import "SubscriberA.h"
#import "SubscriberB.h"

static NSString * const subscriptionNumber1 = @"subscriptionNumber1";
static NSString * const subscriptionNumber2 = @"subscriptionNumber2";

@interface ViewController ()

@property (strong, nonatomic) id<SubscriberProtocol> subA;
@property (strong, nonatomic) id<SubscriberProtocol> subB;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //创建订阅中心
    id<SubscriptionServiceProtocol> serviceCenter = [SubscriptionServiceCenter sharedService];
    //创建订阅号
    [serviceCenter createSubscriptionNumber:subscriptionNumber1];
    [serviceCenter createSubscriptionNumber:subscriptionNumber2];
    //创建订阅者
    _subA = [[SubscriberA alloc] init];
    _subB = [[SubscriberB alloc] init];
    //添加订阅者
    [serviceCenter addSubscriber:_subA withSubscription:subscriptionNumber1];
    [serviceCenter addSubscriber:_subA withSubscription:subscriptionNumber2];
    
    [serviceCenter addSubscriber:_subB withSubscription:subscriptionNumber2];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    //模拟订阅中心发出信息
    id<SubscriptionServiceProtocol> serviceCenter = [SubscriptionServiceCenter sharedService];
    [serviceCenter sendMessage:@"订阅信息1" toSubscriptionNumber:subscriptionNumber1];
    [serviceCenter sendMessage:@"订阅信息2" toSubscriptionNumber:subscriptionNumber2];
}

@end

打印的结果如下:

2019-08-26 23:16:02.371600+0800 ObserverMode[18807:14243197] <SubscriberA: 0x283b48860> -- Message:订阅信息1 -- subscriptionNumber:subscriptionNumber1
2019-08-26 23:16:02.371989+0800 ObserverMode[18807:14243197] <SubscriberB: 0x283b48810> -- Message:订阅信息2 -- subscriptionNumber:subscriptionNumber2
2019-08-26 23:16:02.372205+0800 ObserverMode[18807:14243197] <SubscriberA: 0x283b48860> -- Message:订阅信息2 -- subscriptionNumber:subscriptionNumber2
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

友情链接更多精彩内容