在 LibraryAPI.m 文件引入如下两个文件:
#import "PersistencyManager.h"
#import "HTTPClient.h"
只有在这个地方你才会需要引入这些类。记住:你的 API 将会是你「复杂」系统的唯一的接入点。
现在添加一些私有属性在你的类的扩展里(在 @implementation 上面)
复制代码@interface LibraryAPI () {
PersistencyManager *persistencyManager;
HTTPClient *httpClient;
BOOL isOnline;
}
@end
isOnline 用来判断,如果专辑列表数据发生变化是否能够更新到服务器,例如添加或者删除专辑。
你现在需要在 init 方法中初始化这些变量,在 LibraryAPI.m 中添加下面代码:
复制代码- (id)init
{
self = [super init];
if (self) {
persistencyManager = [[PersistencyManager alloc] init];
httpClient = [[HTTPClient alloc] init];
isOnline = NO;
}
return self;
}
这个 HTTP 客户端在这里并不真正的工作,它只是在外观设计里面起一个示范用法的作用,所以 isOnline 永远是 NO 了。
接下来,在 LibraryAPI.m 里面添加下面三个方法:
复制代码- (NSArray*)getAlbums
{
return [persistencyManager getAlbums];
}
- (void)addAlbum:(Album*)album atIndex:(int)index
{
[persistencyManager addAlbum:album atIndex:index];
if (isOnline)
{
[httpClient postRequest:@"/api/addAlbum" body:[album description]];
}
}
- (void)deleteAlbumAtIndex:(int)index
{
[persistencyManager deleteAlbumAtIndex:index];
if (isOnline)
{
[httpClient postRequest:@"/api/deleteAlbum" body:[@(index) description]];
}
}
看一下 addAlbum:atIndex:。这个类首先更新本地数据,如果联网,它再更新远端服务器。这就是外观设计的长处;当一些系统外的类添加了一个新专辑,它不知道─也不需要知道─复杂的内部系统。










