如何在Swift中实现以下设计模式?
Container
类是用包含字典的JSON数组初始化的。这些字典用于初始化Entry
类。但是,Entry
对象的初始化发生惰性加载,只有当访问entries
或searchEntries
属性时才会进行。
@interface Container
@property (readonly, nonatomic) NSArray *entryDicts;
@property (readonly, nonatomic) NSArray* entries;
@property (readonly, nonatomic) NSDictionary *searchEntries;
@end
@implementation Container
- (instancetype)initWithArray:(NSArray *)array
{
self = [super init];
if (self) {
_entryDicts = array;
}
return self;
}
@synthesize entries = _entries;
- (NSArray *)entries
{
[self loadEntriesIfNeeded];
return _entries;
}
@synthesize entriesByNumber = _entriesByNumber;
- (NSDictionary *)entriesByNumber
{
[self loadEntriesIfNeeded];
return _entriesByNumber;
}
- (void)loadEntriesIfNeeded
{
if (_entries == nil) {
// Load entries
NSMutableArray *entries = [NSMutableArray arrayWithCapacity:[self.entriesDict count]];
NSMutableDictionary *entriesByNumber = [NSMutableDictionary dictionaryWithCapacity:[self.entriesDict count]];
[self.entriesDict enumerateKeysAndObjectsUsingBlock:^(NSString *number, NSDictionary *entryDict, BOOL *stop) {
Entry *entry = [[Entry alloc] initWithDictionary:entryDict container:self];
[entries addObject:entry];
entriesByNumber[number] = entry;
}];
_entries = [entries copy];
_entriesByNumber = [entriesByNumber copy];
// Delete dictionaries
_entriesDict = nil;
}
}
@end