单例模式

透明单例

有一些对象我们往往只需要一个,比如线程池、全局缓存、浏览器中的 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'));

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值