<button id='open'>点击打开</button>
	<button id='close'>关闭弹框</button>
// 弹框创建逻辑,这里我们复用了单例模式面试题的例子
function Modal () {
  let modal = document.getElementById('modal') || null
  if (!modal) {
    modal = document.createElement('div')
    modal.innerHTML = '您还未登录哦~'
    modal.id = 'modal'
    modal.style.display = 'none'
    document.body.appendChild(modal)
  }
  return modal
}
// 定义打开按钮
class OpenButton {
  // 点击后展示弹框(旧逻辑)
  onClick () {
    const modal = Modal()
    modal.style.display = 'block'
  }
}

// 定义按钮对应的装饰器
class Decorator {
  // 将按钮实例传入
  constructor(open_button) {
    this.open_button = open_button
  }

  onClick () {
    this.open_button.onClick()
    // “包装”了一层新逻辑
    this.changeButtonStatus()
  }

  //对话框显示
  changeModal () {
    const modal = document.getElementById('modal')
    modal.style.display = 'none'
  }

  //点击关闭
  closeClick () {
    this.changeModal()
    this.openButton()
  }

  //改变按钮状态
  changeButtonStatus () {
    this.changeButtonText()
    this.disableButton()
  }

  //获取关闭按钮
  disableButton () {
    const btn = document.getElementById('open')
    btn.setAttribute("disabled", true)
  }

  //获取打开按钮
  openButton () {
    const btn = document.getElementById('open')
    btn.removeAttribute("disabled")
  }

  //改变按钮文字
  changeButtonText () {
    const btn = document.getElementById('open')
    btn.innerText = '快去登录'
  }
}

const openButton = new OpenButton()
const decorator = new Decorator(openButton)

document.getElementById('open').addEventListener('click', function () {
  // 此处可以分别尝试两个实例的onClick方法,验证装饰器是否生效
  decorator.onClick()
})

document.getElementById('close').addEventListener('click', function () {
  decorator.closeClick()
})

Last Updated:
Contributors: pengrengui