Javascript写一个缓存代理(AOP)

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

后续会支持缓存异步数据

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 <len; 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"));

猜你喜欢

转载自www.cnblogs.com/fanfan-90/p/12821319.html