外观模式

外观模式

外观模式(Facade Pattern):外部与一个子系统的通信必须通过一个统一的外观对象进行,为子系统中的一组接口提供一个一致的界面,外观模式定义了一个高层接口,这个接口使得这一子系统更加容易使用。外观模式又称为门面模式,它是一种对象结构型模式。

外观模式
封装,隐藏实现细节。简化了操作,简化流程,解耦,简化操作逻辑。
应用,适用场景
o 复杂的子系统,改进使用操作类来操作子系统,通过使用操作类来启用子系统功能。
o 不关心逻辑,只要结果
o ShapeMaker
子系统正逐渐变得复杂。应用模式的过程中演化出许多类。可以使用外观为这些子系统类提供一个较简单的接口。
可以使用外观对子系统进行分层。每个子系统级别有一个外观作为入口点。让它们通过其外观进行通信,可以简化它们的依赖关系。

外观模式的UML类图

外观模式的UML类图.png

这里的Facade类就是门面类,依赖SystemOne、SystemTwo、SystemThree、SystemFour四个系统类,将其封装调用供外部使用。

测试代码:

//买车
- (IBAction)test:(UIButton *)sender {
    Facade* facadeObj = [Facade new];
    [facadeObj buyCars:0];
}

Facade文件:

#import <Foundation/Foundation.h>

@interface Facade : NSObject
-(void)buyCars:(NSInteger)tag;
@end


#import "Facade.h"
#import "SystemOne.h"
#import "SystemTwo.h"
#import "SystemThree.h"

@interface Facade()
@property (strong, nonatomic)SystemOne *one;
@property (strong, nonatomic)SystemTwo *two;
@property (strong, nonatomic)SystemThree *three;

@end

@implementation Facade

#pragma mark - Public

-(void)buyCars:(NSInteger)tag{
    if(tag == 0){
        //  调用两个系统
        [self methodA];
        [self methodB];
    } else {
        //  调用三个系统
        [self methodA];
        [self methodB];
        [self methodC];
    }
}

- (void)methodA {
    NSLog(@"\n方法组 A-------------------------");
    [self.one methodOne];
}

- (void)methodB {
    NSLog(@"\n方法组 B-------------------------");
    [self.two methodTwo];
}

- (void)methodC {
    NSLog(@"\n方法组 C-------------------------");
    [self.three methodThree];
}

#pragma mark - Setters & Getters
- (SystemOne *)one {
    if (!_one) {
        _one = [[SystemOne alloc]init];
    }
    return _one;
}

- (SystemTwo *)two {
    if (!_two) {
        _two = [[SystemTwo alloc]init];
    }
    return _two;
}

- (SystemThree *)three {
    if (!_three) {
        _three = [[SystemThree alloc]init];
    }
    return _three;
}

@end

其他三个系统文件:

#import <Foundation/Foundation.h>
@interface SystemOne : NSObject
- (void)methodOne;
@end

#import "SystemOne.h"
@implementation SystemOne
- (void)methodOne {
    NSLog(@"\nSystemOne methodOne");
}
@end




#import <Foundation/Foundation.h>
@interface SystemTwo : NSObject
- (void)methodTwo;
@end

#import "SystemTwo.h"
@implementation SystemTwo
- (void)methodTwo {
    NSLog(@"\nSystemTwo methodTwo");
}
@end




#import <Foundation/Foundation.h>
@interface SystemThree : NSObject
- (void)methodThree;
@end

#import "SystemThree.h"
@implementation SystemThree
- (void)methodThree {
    NSLog(@"\nSystemThree methodThree");
}
@end
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容