js设计模式--外观模式

来源:互联网 发布:dnf一直网络中断 编辑:程序博客网 时间:2024/05/16 18:52

外观模式
为子系统中的一组接口提供一个一致的界面,Facade模式定义了一个高层接口,这个接口使得这一子系统更加容易使用。隐藏系统的复杂性,并向客户端提供了一个客户端可以访问系统的接口。降低访问复杂系统的内部子系统时的复杂度。在客户端和复杂系统之间再加一层,将调用顺序、依赖关系等处理好。

实例
模拟电脑启动,假设电脑启动顺序:启动CPU,启动内存,启动硬盘,加载数据等。

function CPU() {  this.startup = function () {    console.log("启动CPU");  };}function Memory() {  this.startup = function () {    console.log("启动Memory");  };}function Disk() {  this.startup = function () {    console.log("启动Disk");  };}function Computer() {  var _cpu, _memory, _disk;  _cpu = new CPU();  _memory = new Memory();  _disk = new Disk();  this.start = function () {    _cpu.startup();    _memory.startup();    _disk.startup();  }}computer = new Computer();computer.start();

外观模式优点
1.减少系统相互依赖。
2.提高灵活性。
2.提高了安全性。

适用场景:
1.为复杂的模块或子系统提供外界访问的模块。
2.客户程序与抽象类的实现部分之间存在着很大的依赖性。引入facade 将这个子系统与客户以及其他的子系统分离,可以提高子系统的独立性和可移植性。

再来几个例子:

//Facade.js  var fuhao={  };  fuhao.huofang=function(){      return '馒头';  }  fuhao.chuliliangshi=function(){      return '面粉';  }  fuhao.mantou=function () {      this.chuliliangshi();      this.huofang();  }  //人们想拿到馒头,第一个需要做的就是让系统产生馒头  fuhao.men={      return this.mantou();  }  //stop.js[html] view plain copyvar stopEvent=function(e){      //同时阻止事件默认行为和冒泡      e.stopPropagation();      e.preventDefault();  }  //stopEvent 本身就是生产门面  $('#a').click(function(e){      stopEvent(e);   }  
原创粉丝点击