Facade模式为更大的代码提供了一个方便的高层次接口,可以隐藏其底层的真是复杂性。
能够把它想成是简化API来展现给其余开发人员。css
优势node
缺点jquery
栗子1segmentfault
jquery框架中的$(el),对外提供一个简单接口,实现各类元素的选取,用户没必要手动调用框架内部的各类方法,使用简单,下面提供了简化了的jq DOM选取的实现。设计模式
jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' return new jQuery.fn.init( selector, context, rootjQuery ); }; jQuery.fn = jQuery.prototype = { init: function( selector, context, rootjQuery ) { var match, elem; // HANDLE: $(""), $(null), $(undefined), $(false) if ( !selector ) { return this; } // Handle HTML strings if ( typeof selector === "string" ) { ... } else if ( selector.nodeType ) { ... } else if ( jQuery.isFunction( selector ) ) { ... } return jQuery.makeArray( selector, this ); //将一个 HTMLElements 集合转换成对应的数组对内和merge相同能够操做类数组 } }
.css()同理数组
栗子2框架
这个例子是外观模式和模块模式的组合,对外提供一个更加简单的facade接口。性能
let module = (function() { var _private = { i: 5, get: function() { console.log('current value:' + this.i); }, set: function(val) { this.i = val; }, run: function() { console.log('running'); }, jump: function() { console.log('jumping'); } }, return { facade: function(args) { _private.set(args.val); _private.get(); if(args.run) { _private.run(); } } } }()); module.facade({run: true, value: 10});
《JavaScript设计模式》this
JS设计模式之Module(模块)模式、Revealing Module(揭示模块)模式
JS设计模式之Singleton(单例)模式
JS设计模式之Facade(外观)模式prototype