JavaScript设计模式:单例模式

单例模式

单例模式定义:保证一个类仅有一个实例,并提供一个访问它的全局访问点。
常用的:线程池、全局缓存、浏览器的window对象等

简单的单例模式写法

const Singleton = function (name) {
  this.name = name;
  this.instance = null;
}

Singleton.prototype.getName = function () {
  console.log(this.name);
}
Singleton.getInstance = function (name) {
  console.log('this.instance',this.instance);
  if (!this.instance) {
    this.instance = new Singleton(name);
  }

  return this.instance;
}

const a = Singleton.getInstance('nnn');
const b = Singleton.getInstance('vvvv');
console.log('a', a);
console.log('b', b);
console.log(a === b); //true

在这里插入图片描述

简单的单例模式另一写法

const Singleton = function (name) {
  this.name = name;
}

Singleton.prototype.getName = function () {
  console.log(this.name);
}
Singleton.getInstance = (function () {
  let instance = null;
  return function (name) {
    console.log('instance',instance);
    if (!instance) {
      instance = new Singleton(name)
    }
    return instance;
  }
})()

const a = Singleton.getInstance('nnn');
const b = Singleton.getInstance('vvvv');
console.log('a', a);
console.log('b', b);
console.log(a === b); //true

在这里插入图片描述

用代理模式写一个单例模式

// 一个简单的创建div的类
const CreateDiv = function (html) {
  this.html = html;
  this.init();
}
CreateDiv.prototype.init = function () {
  let div = document.createElement('div');
  div.innerHTML = this.html;
  document.body.appendChild(div);
}

// 负责创建单例
const ProxySingleton = (function () {
  let instance = null;
  return function (html) {
    if (!instance) {
      instance = new CreateDiv(html);
    }
    return instance;
  }
})()

const div = new ProxySingleton('hello-single1')
const div2 = new ProxySingleton('hello-single2')
console.log('div', div, div === div2);

在这里插入图片描述

惰性单例模式

仅在需要的时候创建实例。

const InertiaSingleton = function (fn) {
  let instance = null
  if (!instance) {
    instance = fn.apply(this, arguments)
  }
  return instance;
}
// 
const CreateDiv = function () {
  let div = document.createElement('div');
  div.innerHTML = 'html';
  div.style.display = 'none';
  document.body.appendChild(div);
  return div;
}

const loginDialog = InertiaSingleton(CreateDiv);
// 当需要时再创建实例
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值