單例模式(Singleton Pattern):把一堆代碼放入一個邏輯單元,可通過一個單一的變量來訪問姆钉。最大的好處是封裝代碼说订,減少全局變量。
// 原始寫法潮瓶,全局變量多陶冷,難以維護(hù)
let btn = document.querySelector("#btn")
let div = document.querySelector("#div")
btn.onclick = function () {
????let node = document.createElement("div")
????node.innerText = "hello world"
????div.appendChild(node)
}// 用單例模式,把一坨代碼代碼整合到一個對象里毯辅,作為它的屬性和方法埂伦。只保留一個全局變量,通過預(yù)留的“入口”啟動
let app = {
????init: function () {
????????this.btn = document.querySelector("#btn")
????????this.div = document.querySelector("#div")
????????this.bind()
? ? },
????bind: function () {
????????let _this = this
????????this.btn.onclick = function () {
? ? ? ? ? ? _this.render()
????????}
????},
????render: function () {
????????let node = document.createElement("div")
????????node.innerText = "hello world"
????????this.div.appendChild(node)
????}
}
app.init()// 使用閉包思恐,來隱藏部分不需要暴露的變量沾谜,只暴露出init方法膊毁。這種特殊的單例模式也叫模塊模式(module pattern)
let app = (function () {
????let btn = document.querySelector("#btn")
? ? let div = document.querySelector("#div")
????function bind() {
????????btn.onclick = function () { render() }
? ? }
????function render() {
? ? ? ? let node = document.createElement("div")
????????node.innerText = "hello world"
? ? ? ? div.appendChild(node)
????}
????return {
? ? ? ? init: function () { bind() }
????}
})()
app.init()// 這里對其進(jìn)行一下改進(jìn),不立即創(chuàng)建實例基跑,等需要的時候再創(chuàng)建
let Singleton = (function () {
????let instance
? ? function createInstance() {
? ? ????let btn = document.querySelector("#btn")
? ? ? ? let div = document.querySelector("#div")
? ? ? ? function bind() {
????????????btn.onclick = function () { render() }
? ? ????}
? ? ????function render() {
? ? ? ? ????let node = document.createElement("div")
? ? ? ? ????node.innerText = "hello world"
? ? ? ? ????div.appendChild(node)
? ? ????}
? ? ????return { init: function () { bind() } }
????}
????return {
? ????? getInstance: function () {
????????????if (!instance) { instance = createInstance() }
? ? ? ? ????return instance
????????}
????}
})()
let single = Singleton.getInstance()
single.init()