缓存的概念以及用途
缓存的目的是为了尽量降低获取资源或者数据的时间成本
客户端缓存内容分类
- 资源缓存 (图片、脚本、样式等)
- 数据缓存 (dom数据、对象数据等)
解决: 内存缓存 --> 文件缓存 --> 数据库缓存
缓存简单架构实现
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<script>
//缓存架构应该满足
//1.兼容性
//2.开闭原则
//3.扩展性(尽量满足多种存储)
//4.应用起来方便
(function(global,factory,name){
//函数体
return global[name] = factory.call(global)
})(this,function(){ //this 动态指针引用 // this window //node.js modules //sea.js define
var __E_TYPES__ = {
MEMORY:'MEMORY'
};
//缓存引擎
var __ENGINES__ = {
[__E_TYPES__.MEMORY]:{
init:function(){
this.pools = this.pools||{}
},
set:function(options){
this.pools || this.init();
this.pools[options.key]=options.data
},
get:function(options){
this.pools || this.init();
return this.pools[options.key]
},
remove:function(){
delete this.pools[options.key]
}
},
};
//保护架构的核心功能
var __CACHE__ = {
install:function(type,object){
__E_TYPES__[type]=type;
__ENGINES__[type]=object;
__ENGINES__[type].init();
},
uninstall:function(){},
set:function(type,ops){
__ENGINES__[type].set(ops)
},
get:function(type,ops){
return __ENGINES__[type].get(ops)
},
remove:function(){
return __ENGINES__[type||__E_TYPES__.MEMORY].get(ops)
}
};
//__CACHE__.install(__ENGINES__.MEMORY);
return {
TYPES:__E_TYPES__,
getInstance:function(){
return __CACHE__
}
}
},'MyCache');
var NEC = MyCache.getInstance();
// NEC.install('LOCAL_STORAGE',{
// init:function(){},
// set:function(){},
// get:function(){
// console.log("自调get")
// }
// });
// console.log(MyCache.TYPES,)
NEC.set(MyCache.TYPES.MEMORY,{
key:'jack',
data:{height:144,wight:100}
})
console.log(NEC.get(MyCache.TYPES.MEMORY,{key:'jack'}))
</script>
</body>
</html>