js设计模式——单例模式

289 阅读1分钟

单例模式

什么是单例模式?一个类且只有一个实例的时候,这就是单例模式。

如何创建一个单例模式

new一个类时,需要判断是否之前new过,如果有存在一个实例,则返回当前实例,若没有则创建一个新对象作为实例对象。

面试题,实现单例模式

第一题: 实现一个Storage

实现Storage,使得该对象为单例,基于 localStorage 进行封装。实现方法 setItem(key,value) 和 getItem(key)。

代码如下(class实现)

// 单例模式 —— class实现
class Storage {
  static instance = null
  static getInstance() {
    // 判断是否已经new过1个实例
    if (!Storage.instance) {
      // 若这个实例不存在,那么先创建它
      Storage.instance = new Storage()
    }
    // 若已经创建过实例,则直接返回老的实例对象
    return Storage.instance
  }
  getItem(key) {
    return localStorage.getItem(key)
  }
  setItem(key, value) {
    localStorage.setItem(key, value)
  }
}

const sto = Storage.getInstance()
const sto2 = Storage.getInstance()
sto.setItem('long', 123)
sto.getItem('long'); // 123
sto2.getItem('long'); // 123

第二题: 实现一个全局的模态框

实现一个全局唯一的Modal弹框

<html lang-"en">
‹head›
<meta charset="UTF-8">
<title>单例模式弹框</title>
</head›
<style>
#modal {
    height: 200px;
    width: 200px;
    line-height: 200px;
    position: fixed;
    left: 50%;
    top: 50%;
    transform: translate (-50%,-50%)
    border: 1px solid black;
    text-align: center;
}
</style>
‹body>
<button id="open">打开弹框</button>
<button id="close">关闭弹框</button>
</body>
‹script›
// 创建一个模态框类
class Modal{
    // 获取实例对象
    static getInstance(){
        // 如果不存在实例对象,则创建一个并且插入到文档中
        if(!Modal.instance){
            Modal.instance = document.createElement("div")
            Modal.instance.style.display = 'none'
            Modal.instance.id = "modal"
            Modal.instance.innerText = "我是全局唯一的"
            document.body.appendChild(Modal.instance)
        }
        // 如果存在则返回原来的实例对象
        return Modal.instance
    }
}
function showModal(){
    // 获取实例对象,将其显示
    const modal = Modal.getInstance()
    modal.style.display = 'block'
}
function closeModal(){
    // 获取到实例对象,将其隐藏
    const modal = Modal.getInstance()
    if(modal){
        modal.style.display = 'none'    
    }
}
document.getElementById('open').addEventListener('click',showModal)
document.getElementById('close').addEventListener('click',closeModal)
</script>

经过这两道题,我知道了单例模式的核心思想

  1. getInstance和instance这两个关键词
  2. 以及判断是否存在instance,如果存在则返回现有的instance,如果不存在则创建一个新的