透明单例
有一些对象我们往往只需要一个,比如线程池、全局缓存、浏览器中的 window 对象等。
function Window(name){
this.name = name;
}
Window.prototype.getName = function(){
console.log(this.name)
}
let CreateSingle = function(Constructor){
let instance;
return function(){
if(!instance){
instance = new Constructor(...arguments)
}
return instance
}
}
let createWindow = CreateSingle(Window);
let w1 = createWindow('test1')
let w2 = createWindow('test2')
console.log(w1===w2)
单例模式应用场景:缓存
/*
* 用一个数组来存储数据,给每一个数据项标记一个访问时间戳
* 每次插入新数组项的时候,先把数组中存在的数据项时间戳自增,并将新数组项的时间戳设置为0并插入到数组中
* 每次访问数组中的数据项的时候,将被访问的数据项的时间戳设置为0
当数组空间已满时,将时间戳最大的数据项淘汰
*/
class LRUCache{
constructor(capacity){//容量
this.capacity = capacity;
this.members = []
}
put(key,value){
let found = false;
for(let i=0;i<this.members.length;i++){
let member = this.members[i];
if(member.key == key){
found = true;
this.members[i]={key,value,age:0}
}else{
member.age++;
}
}
if(!found){
if(this.members.length>=this.capacity){
this.members.sort((a,b)=>a.age-b.age).pop();
}
this.members.push({key,value,age:0})
}
}
get(key){
for(let i=0;i<this.members.length;i++){
let member = this.members[i];
if(member.key == key){
member.age = 0;
return member.value;
}
}
return -1;
}
}
let cache = new LRUCache(3);
console.log(cache)
cache.put('1','1')
console.log(cache);
cache.put('2','2')
console.log(cache);
cache.put('3','3')
console.log(cache);
cache.put('4','4')
console.log(cache);
console.log(cache.get('1'));