js設計模式 --- 單例設計模式

js設計模式

設計模式是最佳實踐, 是前輩們在程序設計過程當中總結出的精華, node 出現以前 javascript做爲前端腳本語言不多使用設計模式, 隨着 node 的橫空出世, 已經沒有人能阻擋它的跨領域發展, 是時候思考一下設計模式的 js 實現

往常設計模式在javaEE中討論的比較多, 固然單例設計模式也有不少種實現方法, 在這裏可能至列舉了一些比較筆者認爲傳統的實現方法, 後續會陸續補充完善javascript

單例設計模式

ES5

採用 js 靜態屬性實現, 在類函數上掛載一個實例和一個獲取該事例的方法前端

let Person = (function () {
  function Person(name) {
    this.name = name; 
  }
  Person.getInstance = function(name) {
    if(!this.instance) {
      this.instance = new Person(name);
    }
    return this.instance;
  }
  return Person;
})()

能夠再此基礎上改造 屏蔽該類 禁止外部使用 new 關鍵字, 將前者掛載在類上面獲取事例的函數去掉, 改成直接返回一個具備獲取實例函數的對象java

let Person = (function () {
  function Person(name) {
    this.name = name; 
  }
  return {
    getinstance: function(name) {
      if(!Person.instance) {
        Person.instance = new Person(name);
      }
      return Person.instance;
    }
  };
})()

ES6

此方案與上面採用的是一樣的思路, 只是採用了ES6的語法node

class Dog {
  constructor(name) {
    this.name = name;
  }
  static getInstance(name) {
    if(!this.instance) {
      this.instance = new Dog(name);
    }
    return this.instance;
  }
}
相關文章
相關標籤/搜索