外观模式在复杂的业务系统上提供了简单的接口。如果直接把业务的所有接口直接暴露给使用者,使用者需要单独面对这一大堆复杂的接口,学习成本很高,而且存在误用的隐患。如果使用外观模式,我们只要暴露必要的 API 就可以了。
下图演示了外观模式的基本概念:image.png
API 的使用者完全不知道这内部的业务逻辑有多么复杂。当我们有大量的类并且它们使用起来很复杂而且也很难理解的时候,外观模式是一个十分理想的选择。
外观模式把使用和背后的实现逻辑成功解耦,同时也降低了外部代码对内部工作的依赖程度。如果底层的类发生了改变,外观的接口并不需要做修改。
举个例子,如果有一天你想换掉所有的后台服务,你只需要修改 API 内部的代码,外部调用 API 的代码并不会有改动。
如何使用外观模式
#import
@interface LH4SWaiter : NSObject
//外观模式 用户需要的接口
- (void)buyCarWithCash;// 现金买车
- (void)buyCarWithLoad;// 贷款买车
//全部接口
/**********
// 现金买车
//- (void)buyCarWithCash;
// 贷款买车
- (void)buyCarWithLoad;
// 赠品
- (void)gift;
// 服务
- (void)service;
***********/
@end
#import "LH4SWaiter.h"
#import "LHFinance.h"
#import "LHSales.h"
#import "LHService.h"
@interface LH4SWaiter ()
{
LHFinance *finance;// 财务部门
LHSales *sales;// 销售部门
LHService *service;// 售后服务部门
}
@end
@implementation LH4SWaiter
- (instancetype)init
{
self = [super init];
if (self) {
finance = [[LHFinance alloc] init];
sales = [[LHSales alloc] init];
service = [[LHService alloc] init];
}
return self;
}
// 现金买车
- (void)buyCarWithCash{
// 现金支付
[finance cashPayment];
// 赠送礼品
[self gift];
// 提供服务
[self service];
}
// 贷款买车
- (void)buyCarWithLoad{
BOOL _isSuccess = [finance applyLoan];
// 如果贷款审批下来,则提车、送赠品和服务
if (_isSuccess) {
[sales provideCar];
[self gift];
[self service];
}else{
NSLog(@"贷款审批未通过!");
}
}
// 赠品
- (void)gift{
NSLog(@"赠品有:");
[sales carFilm];
[sales tachograph];
[sales engineGuard];
[sales mat];
}
// 服务
- (void)service{
NSLog(@"售后服务:");
[service carWash];
[service applyPlate];
[service filming];
[service installTachograph];
}
@end
//ViewController
@implementation ViewController
#pragma mark System Method
- (void)viewDidLoad {
[super viewDidLoad];
_waiter = [[LH4SWaiter alloc] init];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
#pragma mark Button Event
// 现金买车
- (IBAction)btnCashEvent:(UIButton *)sender {
[_waiter buyCarWithCash];
}
// 贷款买车
- (IBAction)btnLoanEvent:(UIButton *)sender {
[_waiter buyCarWithLoad];
}
@end