iOS设计模式 - 访问者
原理图
说明
表示一个作用于某对象结构中的各元素的操作,它使你可以在不改变各元素类的前提下定义作用于这些元素的新操作。
源码
https://github.com/YouXianMing/VisitorPattern
// // ElementProtocol.h // VisitorPattern // // Created by YouXianMing on 15/10/27. // Copyright © 2015年 ZiPeiYi. All rights reserved. // #import <Foundation/Foundation.h> @protocol VisitorProtocol; @protocol ElementProtocol <NSObject> /** * 接收访问者 * * @param visitor 访问者对象 */ - (void)accept:(id <VisitorProtocol>)visitor; /** * 元素公共的操作 */ - (void)operation; @end
// // VisitorProtocol.h // VisitorPattern // // Created by YouXianMing on 15/10/27. // Copyright © 2015年 ZiPeiYi. All rights reserved. // #import <Foundation/Foundation.h> #import "ElementProtocol.h" @protocol VisitorProtocol <NSObject> - (void)visitElement:(id <ElementProtocol>)element; @end
// // ElementCollection.h // VisitorPattern // // Created by YouXianMing on 15/10/27. // Copyright © 2015年 ZiPeiYi. All rights reserved. // #import <Foundation/Foundation.h> @protocol ElementProtocol; @interface ElementCollection : NSObject /** * 添加元素 * * @param element 元素 * @param key 元素的键值 */ - (void)addElement:(id <ElementProtocol>)element withKey:(NSString *)key; /** * 获取所有元素的键值 * * @return 所有元素的键值 */ - (NSArray *)allKeys; /** * 根据元素键值获取元素 * * @param key 元素的键值 * * @return 元素 */ - (id <ElementProtocol>)elementWithKey:(NSString *)key; @end
// // ElementCollection.m // VisitorPattern // // Created by YouXianMing on 15/10/27. // Copyright © 2015年 ZiPeiYi. All rights reserved. // #import "ElementCollection.h" #import "ElementProtocol.h" @interface ElementCollection () @property (nonatomic, strong) NSMutableDictionary *elementsDictionary; @end @implementation ElementCollection - (instancetype)init { self = [super init]; if (self) { self.elementsDictionary = [NSMutableDictionary dictionary]; } return self; } - (void)addElement:(id <ElementProtocol>)element withKey:(NSString *)key { NSParameterAssert(element); NSParameterAssert(key); [self.elementsDictionary setObject:element forKey:key]; } - (NSArray *)allKeys { return self.elementsDictionary.allKeys; } - (id <ElementProtocol>)elementWithKey:(NSString *)key { NSParameterAssert(key); return [self.elementsDictionary objectForKey:key]; } @end
细节
原文:http://www.cnblogs.com/YouXianMing/p/4913584.html