单例模式是一个用来划分命名空间并将一批属性和方法组织在一块儿的对象,若是它能够被实例化,那么它只能被实例化一次。
原文连接设计模式
单例模式优势app
并不是全部的对象字面量都是单例,好比模拟数据
基本结构: let Cat = { name: 'Kitty', age: 3, run: ()=>{ console.log('run'); } }
上面对象字面量结构是建立单例模式的方法之一,但并非单例模式,单例模式的特色是仅被实例化一次
要实现单例模式可使用变量来标示该类是否被实例dom
基本实现: class Singleton { constructor(name){ this.name = name; this.instance = null; } getName(){ return this.name; } } let getInstance = (()=> { let instance; return (name)=> { if(!instance) { instance = new Singleton(name); } return instance; } })() let cat1 = getInstance('Hello'); let cat2 = getInstance('Kitty'); console.log(cat1 === cat2); //true console.log(cat1.getName()) //'Hello' console.log(cat2.getName()) //'Hello'
用instance变量标示实例Singleton,若是没有实例建立一个,若是有则直接返回实例,因为仅能被实例化一次,cat2获得的实例和cat1相同this
实用
在建立dom元素时为避免重复建立,可使用单例模式建立设计
//单例模式 let createModal = function() { let content = document.createElement('div'); content.innerHTML = '弹窗内容'; content.style.display = 'none'; document.body.appendChild(content); } //代理获取实例 let getInstance = function(fn) { let result return function() { return result || (result = fn.apply(this,arguments)); } } let createSingleModal = getInstance(createModal); document.getElementById("id").onclick = function(){ let modal = createSingleModal(); modal.style.display = 'block'; };
单例模式是一种简单却很是使用的设计模式,在须要时建立实例,而且只建立惟一一个代理