大话设计模式之外观模式(门面模式)

什么是外观模式


为子系统中的一组接口提供了一个一致的界面,此模式定义了一个高层接口,这个接口使得这一子系统更加容易使用

何时使用外观模式


这要分三个阶段来说,首先,在设计初期阶段,应该要有意识的将不同的两个层分离,比如经典的三层架构,就需要考虑在数据访问层和业务逻辑层,业务逻辑层和表示层的层与层之间建立外观Facada,这样可以为复杂的子系统提供一个简单的jiek,使得耦合大大降低,其次,在开发阶段,子系统往往因为不断的重构演化而变得越来越复杂,大多数的模式使用时也都会产生很多很小的类,这本就是好事,但是也给外部调用他们的用户程序带来了使用上的困难,增加外观Facade 可以提供一个简单的接口,减少他们之间的依赖,第三,在维护一个一流的大型系统时,可能这个系统已经非常难以维护和扩展了,但是因为它包含非常重要的功能,新的需求开发必须要依赖于它,此时用外观模式Facade也是非常合适的,你可以为新系统开发一个外观Facade对象交互,Facade与一流代码交互所有的复杂的工作

 

OC代码实现


SubsystemOne.h

#import <Foundation/Foundation.h>

@interface SubsystemOne : NSObject
-(void)MethodOne;
@end
 

 SubsystemOne.m

#import "SubsystemOne.h"

@implementation SubsystemOne
-(void)MethodOne{
    NSLog(@"方法一");
}
@end

其他的三个子类类似

外观类Facade.h

#import <Foundation/Foundation.h>
#import "SubsystemOne.h"
#import "SubSystemTwo.h"
#import "SubSystemThree.h"
@interface Facade : NSObject
@property(nonatomic,strong)SubsystemOne *one;
@property(nonatomic,strong)SubSystemTwo *two;
@property(nonatomic,strong)SubSystemThree *three;
-(void)MethodA;
-(void)MethodB;
@end

外观类Facade.m

#import "Facade.h"

@implementation Facade
- (instancetype)init
{
    self = [super init];
    if (self) {
        _one=[[SubsystemOne alloc]init];
        _two=[[SubSystemTwo alloc]init];
        _three=[[SubSystemThree alloc]init];
    }
    return self;
}

-(void)MethodA{

    NSLog(@"方法A");
    [_one MethodOne];
    [_two MethodTwo];
    [_three MethodThree];
}
-(void)MethodB{
    NSLog(@"方法B");
    [_one MethodOne];
    [_three MethodThree];
}
@end

客户端

#import <Foundation/Foundation.h>
#import "Facade.h"
int main(int argc, const char * argv[]) {
    @autoreleasepool {
        Facade *facade=[[Facade alloc]init];

        [facade MethodA];
        [facade MethodB];

    }
    return 0;
}

运行结果

总结

适用场景


在以下情况下可以考虑使用外观模式:
(1)设计初期阶段,应该有意识的将不同层分离,层与层之间建立外观模式。
(2) 开发阶段,子系统越来越复杂,增加外观模式提供一个简单的调用接口。
(3) 维护一个大型遗留系统的时候,可能这个系统已经非常难以维护和扩展,但又包含非常重要的功能,为其开发一个外观类,以便新系统与其交互。

优点

(1)实现了子系统与客户端之间的松耦合关系。
(2)客户端屏蔽了子系统组件,减少了客户端所需处理的对象数目,并使得子系统使用起来更加容易。
原文地址:https://www.cnblogs.com/qianLL/p/5272865.html