今天和大家分享的是外观模式。这个模式也不难,我猜想很多人都不经意间用过。好吧,先让我们看看他是如何定义的。
外观模式(Facade),为子系统中的一组接口提供一个一致的界面,此模式定义 一个高层接口,这个接口使得这一子系统更加容易使用。
下面给大家展示一下类的结构图,想必大家一看就明白了:
其实这个模式中,没有类与类之间的继承关系,只是进行了简单的类引用,统一了对外的接口而已。看起来是不是很简单?废话不多说了,下面简单向大家展示一下代码吧!
1
2
3
4
5
| #import <Foundation/Foundation.h>
@interface SubSystemOne:NSObject
-(void)MethodOne;
@end
|
1
2
3
4
5
6
7
| #import "SubSystemOne.h"
@implementation SubSystemOne
-(void)MethodOne{
NSLog(@"子系统方法一");
}
@end
|
1
2
3
4
5
| #import <Foundation/Foundation.h>
@interface SubSystemTwo:NSObject
-(void)MethodTwo;
@end
|
1
2
3
4
5
6
7
| #import "SubSystemTwo.h"
@implementation SubSystemTwo
-(void)MethodTwo{
NSLog(@"子系统方法二");
}
@end
|
1
2
3
4
5
| #import <Foundation/Foundation.h>
@interface SubSystemThree:NSObject
-(void)MethodThree;
@end
|
1
2
3
4
5
6
7
| #import "SubSystemThree.h"
@implementation SubSystemThree
-(void)MethodThree{
NSLog(@"子系统方法三");
}
@end
|
1
2
3
4
5
| #import <Foundation/Foundation.h>
@interface SubSystemFour:NSObject
-(void)MethodFour;
@end
|
1
2
3
4
5
6
7
| #import "SubSystemFour.h"
@implementation SubSystemFour
-(void)MethodFour{
NSLog(@"子系统方法四");
}
@end
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
| #import<Foundation/Foundation.h>
@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
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
| #import "Facade.h"
#import "SubSystemOne.h"
#import "SubSystemTwo.h"
#import "SubSystemThree.h"
#import "SubSystemFour.h"
@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
|
1
2
3
4
5
6
7
8
9
10
11
12
| #import <Foundation/Foundation.h>
#import "Facade.h"
int main (int argc,const char * argv[])
{
@autoreleasepool{
Facade *facade = [[Facade alloc]MyInit];
[facade MethodA];
[facade MethodB];
}
return 0;
}
|
在开发软件时候,考虑使用外观模式的情况一般分为三种情况。第一种情况,设计初始阶段,应该要有意识的将不同的两个分层分离,层与层之间建立外观Facade,这样可以为复杂的子系统提供一个简单的接口,使得耦合大大降低。第二种情况,在开发阶段子系统往往因为不断的重构演化而变得越来越复杂,增加外观Facade可以提供一个简单的接口,减少它们之间的依赖。第三种情况,在维护一个遗留的大型系统时,可能这个系统已经非常难以维护和扩展了,如果有新的需求,那么可以为新系统开发一个外观Facade类,来提供设计粗糙或高度复杂的遗留代码的比较清晰简单的接口,让新系统与Facade对象交互,Facade与遗留代码交互所有复杂的工作,这样可以保持较低的耦合度。
其实,看起来并不难,但是如果想用好还是需要不断的练习和总结啊!
好啦,”打完”收工!