Facade(外觀模式)
為子系統中的一組接口提供一個一致的界面,此模式定義了一個高層接口,這個接口使得這一子系統更加容易使用。
基金經理幫我們管理不同的股票。基金經理作為外觀,我們只需要讓基金經理買或者賣就好,基金經理再幫我們處理不同股票的賣或者買。
項目中有不同的網絡請求,對于每一種類型的網絡請求都封裝到一個固定的文件里處理,比如公用參數添加,返回數據的處理。然后再通過一個外觀文件引入,直接就可以使用了。從使用來說,所有網絡請求的差異都被外觀文件處理了。
還有比如AFN對于NSURLSession的不同系統版本的處理。
VC.m
HCDFound *found = [[HCDFound alloc]init];
[found buyFund];
[found sellFund];
HCDFound.h // 外觀類
@interface HCDFound : NSObject
-(void)buyFund;
-(void)sellFund;
@end
HCDFound.m
@interface HCDFound()
@property(nonatomic,strong)HCDstock1 *stock1;
@property(nonatomic,strong)HCDstock2 *stock2;
@property(nonatomic,strong)HCDstock3 *stock3;
@end
@implementation HCDFound
-(instancetype)init{
self = [super init];
if (self) {
_stock1 = [[HCDstock1 alloc]init];
_stock2 = [[HCDstock2 alloc]init];
_stock3 = [[HCDstock3 alloc]init];
}
return self;
}
-(void)buyFund{
[self.stock1 buy];
[self.stock2 buy];
[self.stock3 buy];
}
-(void)sellFund{
[self.stock1 sell];
[self.stock2 sell];
[self.stock3 sell];
}
@end
HCDstock1.h // 外觀類中的一個子類
@interface HCDstock1 : NSObject
-(void)buy;
-(void)sell;
@end
HCDstock1.m
@implementation HCDstock1
-(void)buy{
NSLog(@"買入股票1");
}
-(void)sell{
NSLog(@"賣出股票1");
}
@end