泉州市建设网站,站长工具域名查询社区,网站域名备案转接入手续,360免费建站方法单例模式
常规单例 单例模式我们在日常使用中还是非常多的#xff0c;比如常见的 jQuery#xff0c;prototype#xff0c;vue等都是属于单例模式#xff0c;我们在使用 new Vue 的时候#xff0c;返回的也会是同一个实例的#xff0c;简单实现
// 方式一
let Car func…单例模式
常规单例 单例模式我们在日常使用中还是非常多的比如常见的 jQueryprototypevue等都是属于单例模式我们在使用 new Vue 的时候返回的也会是同一个实例的简单实现
// 方式一
let Car function () {const inst thisthis.num 0// todo: 其他内容Car function () {return inst}
}const miniCar new Car()
const baoMa new Car()console.log(minicar baoMa) // true// 方式二let Car;(function () {let intr nullCar function Car() {if (intr) {return intr}intr thisthis.name Car// todo: 其他内容}}())const miniCar new Car()
const baoMa new Car()console.log(miniCar baoMa) // true// 方式三let Car function () {let inst thisthis.name Car// todo: 其他内容Car function () { return inst}
}const miniCar new Car()
const baoMa new Car()console.log(miniCar baoMa) // true// 方式四 隐式缓存let Car function () {if (Car.inst) return Car.instthis.name Car// todo: 其他内容Car.inst this
}const miniCar new Car()
const baoMa new Car()console.log(miniCar baoMa) // true正常我们在定义单例模式时应该注重一个自身的命名空间问题很多时候我们更多的可能是直接用一个对象来表达如这种
const Inst {data: () {// todo:},methods: {},...
}
这样就拥有了一个自己的独立命名空间
模块分明
我们在使用时尽可能的将模块分明开来
const Project {common: {// todo:},util: {// todo:},other: {// todo:},...
}// 使用Project.util.xx
一个独立于其他的命名空间其中的代码逻辑分离开来独立模块使得结构更加分明
单例对象
我们可以将一些对象定义为静态
const Car (function () {let opt {SPEED: 100,PRICE:12W}return {get(key) {return opt[key] || null},set(key, value) {opt[key] value}}
}())console.log(Car.get(PRICE)) // 12W
这里我们只能使用 Car 中的 opt 定义的一些属性这里我们定义了方法 set 来写操作若不定义 set 就是我们说的静态了只能读取了
惰性单例
延迟创建
const LazySingle (function () { let _inst nullfunction Single() {return {methods: {// todo:},version:1.0.0}}return function () {if (!_inst) {_inst new Single()}return _inst}
}())let test LazySingle().version
console.log(test) // 1.0.0
所谓单例就是在一个文件或是一个系统中只能存在一个实例或是一个对象尽可能的将各个模块的代码梳理得井井有条更为规范