Javascript写一个缓存代理(AOP)

2021-01-30 05:15

阅读:735

标签:join   UNC   tostring   rip   函数   new   object   支持   turn   

自己写了一个缓存代理,使用代理模式,支持指定函数、支持按参数缓存,原创

后续会支持缓存异步数据

CacheProxy:

function CacheProxy(obj,proxyMethods){
        var _cache={};
        var _getType=Object.prototype.toString;  
        var _this = this;
        var _getCacheName=function(methodName,args){
            var caches = [];
            caches.push(methodName);
            for (var i = 0,len=args.length; i ) {
                caches.push(args[i]);
            }
            return caches.join(_);
        };
        if (_getType.apply(obj)!=="[object Object]") {
            console.info("parameter obj must be object");
            return;
        }
        if (_getType.apply(proxyMethods)!=="[object Array]") {
            if (proxyMethods===undefined ) {
                proxyMethods=[];
            }
            else{
                console.info("parameter proxyMethods must be Array");
                return;                
            }
        }

        for(attr in obj){
            if(_getType.apply(obj[attr])==="[object Function]"){
                (function(attr){
                   _this[attr]=function(){
                    if (proxyMethods.length===0 || proxyMethods.indexOf(attr)>-1) {
                        var cacheName = _getCacheName(attr,_this[attr].arguments);
                        if (_cache[cacheName]!==undefined) {
                            return _cache[cacheName]+"_cache";
                        }
                        _cache[cacheName] = obj[attr].apply(_this,arguments);
                        return _cache[cacheName];
                    }
                    
                    return obj[attr].apply(_this,arguments);
                }; 
            })(attr);
                
            }
        }

客户端:

    function Person(){
        this.sayName=function(a,b,c){
            return "fan";
        };
        this.sayHello=function(a,b){
            return "Hello";
        };
    }

var p = new Person();
var cacheProxy = new CacheProxy(p,["sayName","sayHello"]);//第二个参数可以不写
console.info(cacheProxy.sayName());
console.info(cacheProxy.sayName("1"));
console.info(cacheProxy.sayName("1","2"));
console.info(cacheProxy.sayName("1","2"));
console.info(cacheProxy.sayName("1"));
console.info(cacheProxy.sayName("1"));
 
console.info(cacheProxy.sayHello());
console.info(cacheProxy.sayHello("1"));
console.info(cacheProxy.sayHello("1","2"));
console.info(cacheProxy.sayHello("1","2"));

 

Javascript写一个缓存代理(AOP)

标签:join   UNC   tostring   rip   函数   new   object   支持   turn   

原文地址:https://www.cnblogs.com/fanfan-90/p/12821319.html


评论


亲,登录后才可以留言!