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