外觀模式(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 里面添加下面三個方法:
提示:當在你的子系統里設計一個外觀類的時候,記住沒有任何東西可能阻止客戶訪問這些「隱藏」類。要多寫些防御性的代碼,不要想當然的認為所有客戶都會用同樣的方式使用你的外觀類。
運行你的程序,你會看一個黑底空白內容的屏幕,像下面這樣:
新聞熱點
疑難解答