10個每一個開發人員都喜歡的JavaScript模式

英文 | https://medium.com/javascript-in-plain-english/top-10-javascript-patterns-every-developers-like-fa79b5400cc1
翻譯 | web前端開發(ID:web_qdkf)

一、構造器模式

在面向對象的編程語言中,構造函數是一種特殊的方法,用於在爲其分配了內存後初始化新建立的對象。在JavaScript中,幾乎全部東西都是對象,咱們最常對對象構造函數感興趣。
例如,因爲對象構造函數用於建立特定類型的對象,所以準備對象以供使用和接受參數時,構造函數可在首次建立對象時用來設置成員屬性和方法的值。

如咱們所見,JavaScript不支持類的概念,所以在構造函數內部,此關鍵字引用正在建立的新對象並從新訪問對象建立,基本的構造函數可能以下所示:
  
    
  
  
   
   
            
   
   
    
      
    
    
     
     
              
     
     
function Car(model, year, miles) { this.model = model; this.year = year; this.miles = miles;}// Usage:var bmw = new Car('M4', '2019', '1000');

二、moModuleattern

模塊是任何健壯的應用程序體系結構中不可或缺的一部分,一般有助於保持項目代碼單元的清晰分離和組織實現模塊有多種選擇。
這些包括:
  • 對象文字符號javascript

  • 模塊模式前端

  • AMD模塊java

  • CommonJS模塊web

  • ECMAScript Harmony模塊編程

對象文字:
  
    
  
  
   
   
            
   
   
    
      
    
    
     
     
              
     
     
var newObject = { variableKey:variableValue, functionKey:function(){ //… }};
模塊模式:

讓咱們開始經過建立一個獨立的模塊來研究Module模式的實現。
  
    
  
  
   
   
            
   
   
    
      
    
    
     
     
              
     
     
var testModule = (function() { var counter = 0; return { incrementCounter: function() { return ++counter; }, resetCounter: function() { counter = 0; } };})();// Usage:testModule.incrementCounter();testModule.resetCounter();

三、顯示模塊模式

顯示模塊能夠作的一件事是,當咱們要從另外一個對象調用一個公共方法或訪問公共變量時,避免重複主對象的名稱。
  
    
  
  
   
   
            
   
   
    
      
    
    
     
     
              
     
     
var myRevealingModule = (function() { var privateVariable = 'not okay', publicVariable = 'okay'; function privateFun() { return privateVariable; }function publicSetName(strName) { privateVariable = strName; }function publicGetName() { privateFun(); }return { setName: publicSetName, message: publicVariable, getName: publicGetName };})();//Usage:myRevealingModule.setName('Marvin King');

四、單例模式

這樣就知道了Singleton模式,由於它將類的實例化限制爲單個對象。單例不一樣於靜態類,由於咱們能夠延遲其初始化。一般,由於它們須要一些在初始化期間可能不可用的信息。對於不知道先前引用它們的代碼,它們沒有提供易於檢索的方法。讓咱們看一下單例的結構:
  
    
  
  
   
   
            
   
   
    
      
    
    
     
     
              
     
     
var singletonPattern = (function() { var instance; function init() { // Singleton function privateMethod() { console.log('privateMethod'); } var privateVariable = 'this is private variable'; var privateRandomNumber = Math.random(); return { publicMethod: function() { console.log('publicMethod'); }, publicProperty: 'this is public property', getRandomNumber: function() { return privateRandomNumber; } }; }return { // Get the singleton instance if one exists // or create if it doesn't getInstance: function() { if (!instance) { instance = init(); } return instance; } };})();// Usage:var single = singletonPattern.getInstance();

五、觀察者模式

觀察者是一種設計模式,其中對象根據觀察者維護對象列表,並自動將狀態的任何更改通知它們。
  • 學科
  • 維護觀察者列表,添加或刪除觀察者的設施
  • 觀察者
  • 爲須要通知受試者狀態變化的對象提供更新的接口
  • 具體主題
  • 向狀態觀察者廣播通知,存儲具體觀察者的狀態
  • 具體觀察者
  • 存儲對ConcreteSubject的引用,爲觀察者實現更新的接口,以確保狀態與主題一致
  
    
  
  
   
   
            
   
   
    
      
    
    
     
     
              
     
     
function ObserverList() { this.observerList = [];}ObserverList.prototype.Add = function(obj) { return this.observerList.push(obj);};ObserverList.prototype.Empty = function() { this.observerList = [];};ObserverList.prototype.Count = function() { return this.observerList.length;};ObserverList.prototype.Get = function(index) { if (index > -1 && index < this.observerList.length) { return this.observerList[index]; }};//...
當主題須要將一些有趣的事情通知觀察者時,它會向觀察者廣播通知(包括與通知主題相關的特定數據)
當咱們再也不但願特定觀察者經過其註冊的主題來通知其更改時,該主題能夠將其從觀察者列表中刪除。未來,我將更多地討論如何在JavaScript中普遍使用觀察者的功能。

六、中介者模式

若是系統之間組件之間的直接關係過多。該組件就是能夠經過控件進行通訊的中心點了。中介體模式經過確保組件而不是彼此明確引用來促進鬆散耦合。
  
    
  
  
   
   
            
   
   
    
      
    
    
     
     
              
     
     
var mediator = (function() { var topics = {}; var subscribe = function(topic, fn) { if (!topics[topic]) { topics[topic] = []; } topics[topic].push({ context: this, callback: fn }); return this; };// publish/broadcast an event to the rest of the application var publish = function(topic) { var args; if (!topics[topic]) { return false; } args = Array.prototype.slice.call(arguments, 1); for (var i = 0, l = topics[topic].length; i < l; i++) { var subscription = topics[topic][i]; subscription.callback.apply(subscription.content, args); } return this; }; return { publish: publish, subscribe: subscribe, installTo: function(obj) { obj.subscribe = subscribe; obj.publish = publish; } };})();

七、原型模式

使用Prototype模式的好處之一是,咱們已經利用JavaScript原生提供的原型優點,而不是嘗試模仿其餘語言的功能。讓咱們看一下模式示例。
  
    
  
  
   
   
            
   
   
    
      
    
    
     
     
              
     
     
var myCar = { name: 'bmw', drive: function() { console.log('I am driving!'); }, panic: function() { console.log('wait, how do you stop this thing?'); }};//Usages:var yourCar = Object.create(myCar);console.log(yourCar.name); //'bmw'

八、工廠模式

Factory能夠提供用於建立對象的通用接口,咱們能夠在其中指定但願建立的工廠對象的類型。
請參見下圖。

    
      
    
    
     
     
              
     
     
function Car(options) { this.doors = options.doors || 4; this.state = options.state || 'brand new'; this.color = options.color || 'silver';}

九、Mixin模式

混合類是提供功能的類,這些功能能夠由子類或子類組輕鬆繼承以進行功能複用。
  
    
  
  
   
   
            
   
   
    
      
    
    
     
     
              
     
     
var Person = function(firstName, lastName) { this.firstName = firstName; this.lastName = lastName; this.gender = 'male';};var clark = new Person('Clark', 'kent');var Superhero = function(firstName, lastName, powers) { Person.call(this.firstName, this.lastName); this.powers = powers;};SuperHero.prototype = Object.create(Person.prototype);var superman = new Superhero('Clark', 'Kent', ['flight', 'heat-vision']);console.log(superman); //output personal attributes as well as power
在這種狀況下,超級英雄可以用特定於其對象的值覆蓋任何繼承的值。

十、裝飾器模式

裝飾器是一種結構設計模式,旨在促進代碼重用。與Mixins類似,它們能夠被認爲是對象子類化的另外一種可行選擇。傳統上,裝飾器提供了將行爲動態添加到系統中現有類的功能。這個是裝飾器自己不應有的基本功能。讓咱們看看它市如何在JavaScript中進行工做的。
  
    
  
  
   
   
            
   
   
    
      
    
    
     
     
              
     
     
function MacBook() { this.cost = function() { return 997; }; this.screenSize = function() { return 11.6; };}// Decorator 1function Memory(macbook) { var v = macbook.cost(); macbook.cost = function() { return v + 75; };}// Decorator 2function Engraving(macbook) { var v = macbook.cost(); macbook.cost = function() { return v + 200; };}// Decorator 3function Insurance(macbook) { var v = macbook.cost(); macbook.cost = function() { return v + 250; };}var mb = new MacBook();Memory(mb);Engraving(mb);Insurance(mb);mb.cost(); // 1522
全部模式均可能不適用於一個項目,而且某些項目可能會受益於Observer模式提供的去耦收益。也就是說,一旦咱們緊緊掌握了設計模式及其最適合的解決特定問題的技巧的話,將它集成到咱們的應用程序體系結構中變得更加容易。

本文分享自微信公衆號 - web前端開發(web_qdkf)。
若有侵權,請聯繫 support@oschina.cn 刪除。
本文參與「OSC源創計劃」,歡迎正在閱讀的你也加入,一塊兒分享。設計模式

相關文章
相關標籤/搜索