单例模式:
**好处:**减少全局变量,全局对象被污染问题
实现:
-
懒汉式
let ShopCar = (function () { let instance; function init() { /*这里定义单例代码*/ return { buy(good) { this.goods.push(good); }, goods: [], }; } return { getInstance: function () { if (!instance) { instance = init(); } return instance; }, }; })(); let car1 = ShopCar.getInstance(); let car2 = ShopCar.getInstance(); car1.buy('橘子'); car2.buy('苹果'); console.log(car1.goods); //[ '橘子', '苹果' ] console.log(car1 === car2); // true
-
饿汉式
面试题 -> 实现Storage,使得该对象为单例,基于 localStorage 进行封装。实现方法 setItem(key,value) 和 getItem(key)
class Storage {
static getInstance() {
if(!Storage