打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
设计模式之外观模式(门面模式)
门面模式(Facade Pattern)也叫做外观模式
这种类型的设计模式属于结构性模式。
定义:
Provide a unified interface to a set of interfaces in a subsystem.Facade defines a higher-level interface that makes the subsystem easier to use.
要求一个子系统的外部与其内部的通信必须通过一个统一的对象进行。门面模式提供一个高层次的接口,使得子系统更易于使用。
理解
外观模式(Facade)他隐藏了系统的复杂性,并向客户端提供了一个可以访问系统的接口。为子系统中的一组接口提供了一个统一的访问接口,这个接口使得子系统更容易被访问或者使用
应用场景
为一个复杂的模块或子系统提供一个供外界访问的接口
子系统相对独立——外界对子系统的访问只要黑箱操作即可
预防低水平人员带来的风险扩散
举例:
Android 的 Context
使用一个Context对象来发送广播—使用门面对象Context的sendBroadcast方法来实现对ActivityManagerNative类的访问
使用一个Context对象来启动服务—使用门面对象Context的startService方法来实现对ActivityManagerNative类的访问。
使用一个Context对象来启动activity—使用门面对象Context的startActivity方法来实现对mMainThread.getInstrumentation()的访问。
使用一个Context对象来获取PackageManager信息—使用门面对象Context的getPackageManager()方法来实现的ApplicationPackageManager类的访问。
现实中的 房东(subsystem classes) 和 中介(Facade) 租户(client)
uml图示例
代码示例:
子系统
1
2
3
4
5
6
7
8
9
10
11
12
/** * 法师 * * @author Administrator * */public class Master { public void CreateMaster() { System.out.println("法师型小怪!"); }}
1
2
3
4
5
6
7
8
9
10
11
12
/** * 战士 * * @author Administrator * */public class Warrior { public void CreateWarrior() { System.out.println("战士型小怪!"); }}
1
2
3
4
5
6
7
8
9
10
11
12
/** * 弓箭手 * * @author Administrator * */public class Archer { public void CreateArcher() { System.out.println("弓手型小怪!"); }}
Facade–门面对象:
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
/** * 门面 * @author Administrator * */public class Facade { private Master master = new Master(); private Warrior warrior = new Warrior(); private Archer archer = new Archer(); public void CreateMaster() { this.master.CreateMaster(); } public void CreateWarrior() { this.warrior.CreateWarrior(); } public void CreateArcher() { this.archer.CreateArcher(); }}
客户端:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/** * 客户端 * @author Administrator * */public class Client { public static void main(String[] args) { // TODO Auto-generated method stub Facade facade = new Facade(); facade.CreateMaster(); facade.CreateWarrior(); facade.CreateArcher(); }}
输出结果:
2
3
4
法师型小怪!战士型小怪!弓手型小怪!
门面模式的优点
松散耦合
简单易用
提高安全性
更好的的划分访问的层次
提高了灵活性
依赖减少了,灵活性自然提高了。不管子系统内部如何变化,只要不影响到门面对象,
任你自由活动。
门面模式的缺点
门面模式最大的缺点是不符合开闭原则,对修改关闭,对扩展开放。门面模式中门面对象是重中之重,一旦系统投入产生,如果发现了有错误,你怎么解决?完全遵从开闭原型,根本没有办法解决。继承?覆写?都用不上。唯一能做的就是修改门面对象的代码,这个风险是相当大的。请大家要注意。
模式小结
门面模式的本质就是:封装交互,简化调用。
Facade封装了子系统外部与子系统内部多个模块的交互过程,从而简化了外部的调用
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
外观模式(Facade Pattern)
设计模式——门面模式(Facade)
13. 门面模式
C#设计模式(11)——外观模式(Facade Pattern)
Java设计模式-外观(门面)模式
PHP设计模式之门面模式
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服