Pages

Tuesday, February 18, 2014

JS: Singleton based Cache

Here is the cache class based on singleton design pattern in javascript. There are 2 alternatives present in here.
/* 
@file CCache.js
@author Abhishek Kumar
@email akbittu@gmail.com
*/

// Singleton Class - Alternate#1
var CCache = (function () {
    var instance;    
    function init() {
        var cache = {};
        return {
            getCacheItem: function (itemId) {
                return cache[itemId];
            },
            setCacheItem: function (itemId, itemVal) {
                cache[itemId] = itemVal;
            }
        };
    };
    return {
        getInstance: function () {
            if (!instance) {
                instance = init();
            }
            return instance;
        }
    };
})();

// Usage
var oCache = CCache.getInstance();
oCache.setCacheItem('dataHolder', 'a new item value');
config.log(oCache.getCacheItem('dataHolder'));

// Singleton Class - Alternate#2
function CCache() {
    if (arguments.callee._singletonInstance) {
        return arguments.callee._singletonInstance;
    }
    arguments.callee._singletonInstance = this;

    var cache = {};        
    this.getCacheItem = function (itemId) {
        return cache[itemId];
    };
    this.setCacheItem = function (itemId, itemVal) {
        cache[itemId] = itemVal;
    };
}

// Usage
var oCache = new CCache();
oCache.setCacheItem('dataHolder', 'a new item value');
config.log(oCache.getCacheItem('dataHolder'));

No comments:

Post a Comment