阿大次德,猎场迅雷下载,英雄联盟排队
外观模式(facade),为子系统中的一组接口提供一个一致的界面,此模式定义 一个高层接口,这个接口使得这一子系统更加容易使用。
下面给大家展示一下类的结构图,想必大家一看就明白了:
其实这个模式中,没有类与类之间的继承关系,只是进行了简单的类引用,统一了对外的接口而已。看起来是不是很简单?废话不多说了,下面简单向大家展示一下代码吧!
注意:本文所有代码均在arc环境下编译通过。
subsystemone类接口
@interface subsystemone:nsobject
-(void)methodone;
@end
@implementation subsystemone
-(void)methodone{
nslog(@"子系统方法一");
}
@end
@interface subsystemtwo:nsobject
-(void)methodtwo;
@end
@implementation subsystemtwo
-(void)methodtwo{
nslog(@"子系统方法二");
}
@end
@interface subsystemthree:nsobject
-(void)methodthree;
@end
@implementation subsystemthree
-(void)methodthree{
nslog(@"子系统方法三");
}
@end
@interface subsystemfour:nsobject
-(void)methodfour;
@end
@implementation subsystemfour
-(void)methodfour{
nslog(@"子系统方法四");
}
@end
@class subsystemone;//此处@class关键字的作用是声明(不是定义哦)所引用的类
@class subsystemtwo;
@class subsystemthree;
@class subsystemfour;
@interface facade :nsobject{
@private subsystemone *one;
@private subsystemtwo *two;
@private subsystemthree *three;
@private subsystemfour *four;
}
-(facade*)myinit;
-(void)methoda;
-(void)methodb;
@end
@implementation facade
-(facade*)myinit{
one= [[subsystemone alloc]init];
two= [[subsystemtwo alloc]init];
three= [[subsystemthree alloc]init];
four= [[subsystemfour alloc]init];
return self;
}
-(void)methoda{
nslog(@"\n方法组a() ---- ");
[one methodone];
[two methodtwo];
[three methodthree];
[four methodfour];
}
-(void)methodb{
nslog(@"\n方法组b() ---- ");
[two methodtwo];
[three methodthree];
}
@end
int main (int argc,const char * argv[])
{
@autoreleasepool{
facade *facade = [[facade alloc]myinit];
[facade methoda];
[facade methodb];
}
return 0;
}
实例进阶
目前你有 persistencymanager 来在本地存储专辑数据,httpclient 处理远程通信。项目中其它的类跟这些逻辑都没关。
执行这个模式,只有 libraryapi 来保存 persistencymanager 和 httpclient 的实例。之后,libraryapi 将会公开一个简单的 api 来访问这些服务。
libraryapi 将会公开给其它代码,但是它隐藏了 app 中 httpclient 和 persistencymanager 的复杂部分。
打开 libraryapi.h,在顶部引入面文件:
#import "album.h"
接下来,在 libraryapi.h下面添加如下方法:
在 libraryapi.m 文件引入如下两个文件:
#import "persistencymanager.h"
#import "httpclient.h"
只有在这个地方你才会需要引入这些类。记住:你的 api 将会是你「复杂」系统的唯一的接入点。
现在添加一些私有属性在你的类的扩展里(在 @implementation 上面)
你现在需要在 init 方法中初始化这些变量,在 libraryapi.m 中添加下面代码:
接下来,在 libraryapi.m 里面添加下面三个方法:
- (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]];
}
}
提示:当在你的子系统里设计一个外观类的时候,记住没有任何东西可能阻止客户访问这些「隐藏」类。要多写些防御性的代码,不要想当然的认为所有客户都会用同样的方式使用你的外观类。
运行你的程序,你会看一个黑底空白内容的屏幕,像下面这样:
如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复
网友评论