分享

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

 东西VS南北 2017-11-22
门面模式(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对象来发送广播—使用门面对象ContextsendBroadcast方法来实现对ActivityManagerNative类的访问

使用一个Context对象来启动服务—使用门面对象ContextstartService方法来实现对ActivityManagerNative类的访问。

使用一个Context对象来启动activity—使用门面对象ContextstartActivity方法来实现对mMainThread.getInstrumentation()的访问。

使用一个Context对象来获取PackageManager信息—使用门面对象ContextgetPackageManager()方法来实现的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封装了子系统外部与子系统内部多个模块的交互过程,从而简化了外部的调用




    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多