国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > JavaScript > 正文

js單例模式詳解實例

2024-05-06 15:55:51
字體:
來源:轉載
供稿:網友
這篇文章主要介紹了什么是單例單例模式、使用場景,提供了3個示例給大家參考

什么是單例?

單例要求一個類有且只有一個實例,提供一個全局的訪問點。因此它要繞過常規的控制器,使其只能有一個實例,供使用者使用,而使用著不關心有幾個實例,因此這是設計者的責任

復制代碼 代碼如下:


In JavaScript, Singletons serve as a shared resource namespace which isolate implementation code from the global namespace so as to provide a single point of access for functions.

在javascript中,單例被當做一個全局的命名空間,提供一個訪問該對象的一個點。

使用場景

復制代碼 代碼如下:


In practice, the Singleton pattern is useful when exactly one object is needed to coordinate others across a system.


單例比較適用于一個對象和其他系統進行交互。

類比

單例有點類似于一個小組的小組長,在一段時間內只有一個小組長,有小組長來指定組員的工作,分配和協調和組員的工作。

實例1:這個是最簡單的單例,通過key,value的形式存儲屬性和方法

復制代碼 代碼如下:


var A = {
   xx:3,
   yy:4,
   B:function(el){

   },
   C:function(el){

   },
   D:function(el){

   },
   E:function(el){

   }
}


實例2:首先創建一個實例的引用,然后判斷這個實例是否存在,如果不存在那么就創建,存在的話,就直接返回,保證有且只有一個。

復制代碼 代碼如下:


var mySingleton = (function () {

// Instance 存儲一個單例實例的引用
var instance;

function init() {

// Singleton

// 私有的方法和變量
function privateMethod(){
    console.log( "I am private" );
}

var privateVariable = "Im also private";

return {

  // 共有的方法和變量
  publicMethod: function () {
    console.log( "The public can see me!" );
  },

  publicProperty: "I am also public"
};

};

return {

// 如果實例不存在,那么創建一個
getInstance: function () {

  if ( !instance ) {
    instance = init();
  }

  return instance;
}

};

})();

var singleA = mySingleton;
var singleB = mySingleton;
console.log( singleA === singleB ); // true

實例3:

復制代碼 代碼如下:


var SingletonTester = (function () {
  // options: an object containing configuration options for the singleton
  // e.g var options = { name: "test", pointX: 5};
  function Singleton( options )  {
    // set options to the options supplied
    // or an empty object if none are provided
    options = options || {};
    // set some properties for our singleton
    this.name = "SingletonTester";
    this.pointX = options.pointX || 6;
    this.pointY = options.pointY || ;
  }
  // our instance holder
  var instance;
  // an emulation of static variables and methods
  var _static  = { 
    name:  "SingletonTester",
    // Method for getting an instance. It returns
    // a singleton instance of a singleton object
    getInstance:  function( options ) {  
      if( instance  ===  undefined )  {   
        instance = new Singleton( options );  
      }  
        return  instance;     
    }
  };
  return  _static;
})();
var singletonTest  =  SingletonTester.getInstance({
  pointX:  5
});
// Log the output of pointX just to verify it is correct
// Outputs: 5
console.log( singletonTest.pointX );

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

圖片精選

主站蜘蛛池模板: 调兵山市| 石门县| 乌拉特后旗| 巴林右旗| 历史| 洛阳市| 洮南市| 蕲春县| 闻喜县| 聂荣县| 南丹县| 基隆市| 枣庄市| 惠州市| 万源市| 蓬溪县| 富阳市| 罗源县| 鞍山市| 阿克陶县| 沂水县| 湄潭县| 泰安市| 大同县| 麻阳| 崇左市| 亚东县| 满洲里市| 洪泽县| 九江县| 普格县| 徐闻县| 岐山县| 陇川县| 隆回县| 调兵山市| 化德县| 西青区| 凤凰县| 新丰县| 卫辉市|