最近看到老大写了一段神奇的代码,感觉终于js中听过没用过的设计模式突然有了意义,这里记录一下:
class Cache {
constructor() {
this.storage = {};
}
set(k, v) {
this.storage[k] = v;
}
get(k) {
return this.storage[k];
}
destroy(k) {
if (this.storage[k].destroy) {
this.storage[k].destroy();
} else {
delete this.storage[k];
}
}
}
export default new Cache();
最开始我以为这里只是返回一个Cache类,但是在debug代码的时候发现constructor只执行了一次,让我们来回顾一下单例模式的定义:只允许实例化一次,可以用一个对象划一个命名空间,用于避免命名重复的问题,帮助管理静态变量(只能访问不能修改)具体信息可以查看我之前的文章。
因而这里Cache方法就为外部提供了一种方法来管理变量。