zoukankan      html  css  js  c++  java
  • 单例模式

    单例模式: 保证一个类只有一个实例,一般先判断实例是否存在,如果存在直接返回,不存在则先创建再返回,这样就可以保证一个类只有一个实例对象。

    作用:

    (1)、保证某个类的对象的唯一性;

    (2)、模块间通信;

    (3)、防止变量污染

     1 function Singleton(name) {
     2        this.name = name;
     3        this.instance = null;
     4   }
     5 Singleton.prototype.getName = function () {
     6         console.log(this.name, 1)
     7  }
     8  Singleton.getInstance = function (name) {
     9     if (!this.instance) {
    10           this.instance = new Singleton(name);
    11         }
    12            return this.instance;
    13      }
    14   var a = Singleton.getInstance('sven1');
    15   var b = Singleton.getInstance('sven2');
    16   // 指向的是唯一实例化的对象
    17   console.log(a === b, a.getName());

    es6实现

     1 class Demo1{
     2     private static instance:Demo1;
     3     private constructor(public name:string){}
     4     static getInstance(name:string){
     5         if(!this.instance){
     6             this.instance=new Demo1(name)
     7         }
     8         return this.instance
     9     }
    10 }
    11 const d1=Demo1.getInstance('')
    12 const d2=Demo1.getInstance('')
    13 console.log(d1,d2,d1==d2)
    14 //小 小 true 
    15 // 指向的是唯一实例化的对象
  • 相关阅读:
    Redpine的Lite-Fi解决方案获Wi-Fi CERTIFIED认证
    植物园偶遇一直喵
    美食篇
    端午节路过南站
    黄山云海
    一品黄山 天高云淡
    黄山的日出日落
    宏村,寻找你的前世今生
    git把本地文件上传到github上的步骤
    一张照片一个故事
  • 原文地址:https://www.cnblogs.com/studyWeb/p/13156822.html
Copyright © 2011-2022 走看看