在 Vue 中使用设计模式非常简单,只需要在代码中引入设计模式的实现即可。
以单例模式为例,你可以这样实现:
const Singleton = (function() {
let instance
function createInstance() {
const object = new Object({ name: 'singleton' })
return object
}
return {
getInstance: function() {
if (!instance) {
instance = createInstance()
}
return instance
}
}
})()
const instance1 = Singleton.getInstance()
const instance2 = Singleton.getInstance()
console.log(instance1 === instance2) // true