JS設(shè)計(jì)模式(三) 數(shù)據(jù)訪問對象模式

引言

HTML5 提供了兩種在客戶端存儲(chǔ)數(shù)據(jù)的新方法:localStorage、sessionStorage,他們是Web Storage API 提供的兩種存儲(chǔ)機(jī)制,區(qū)別在于前者屬于永久性存儲(chǔ),而后者是局限于當(dāng)前窗口的數(shù)據(jù)傳遞,存儲(chǔ)在其中的數(shù)據(jù)會(huì)在當(dāng)前會(huì)話結(jié)束時(shí)被刪除。localStorage、sessionStorage的具體內(nèi)容在這里就不多做介紹了,我們主要探討一下在實(shí)際開發(fā)中怎樣合理使用他們。

問題

大部分網(wǎng)站會(huì)將一些數(shù)據(jù)(如:用戶Token)存儲(chǔ)在前端,用來實(shí)現(xiàn)頁面間的傳值,對于一些大型Web應(yīng)用來說,其存儲(chǔ)的數(shù)據(jù)可能會(huì)非常多,數(shù)據(jù)的管理會(huì)變得復(fù)雜,并且一個(gè)大型項(xiàng)目是由多位程序員共同開發(fā)的,這時(shí)就會(huì)遇到一個(gè)問題:怎樣確保自己的數(shù)據(jù)不會(huì)覆蓋掉其他人的呢?因?yàn)樵谝粋€(gè)頁面中大家都是使用同一個(gè)WebStorage對象,總不能把大家使用過的Key記錄下來吧。這時(shí)候就可以使用數(shù)據(jù)訪問對象模式來解決了。

數(shù)據(jù)訪問對象模式(DAO)

數(shù)據(jù)訪問對象模式就是對數(shù)據(jù)源的訪問與存儲(chǔ)進(jìn)行封裝,提供一個(gè)數(shù)據(jù)訪問對象類負(fù)責(zé)對存儲(chǔ)的數(shù)據(jù)進(jìn)行管理和操作,規(guī)范數(shù)據(jù)存儲(chǔ)格式,類似于后臺(tái)的DAO層。
由于WebStorage采用Key-Value的方式存取數(shù)據(jù),而且只能存字符串(任何類型存儲(chǔ)的時(shí)候都會(huì)被轉(zhuǎn)為字符串,讀取的時(shí)候需要進(jìn)行類型轉(zhuǎn)換),所以我們可以對Key的格式進(jìn)行規(guī)范,比如模塊名+Key,開發(fā)人員+Key等,還可以在值中添加一段前綴用來描述數(shù)據(jù),如添加數(shù)據(jù)過期日期的時(shí)間戳,用來管理數(shù)據(jù)的生命周期。具體格式項(xiàng)目組可以自己定義,主要是便于管理,防止出現(xiàn)沖突,約定好規(guī)范后就可以開始定義數(shù)據(jù)訪問對象了。

下面以localStorage為例,介紹一下數(shù)據(jù)訪問對象類的定義和使用。

代碼示例

DAO類基本結(jié)構(gòu)

數(shù)據(jù)訪問對象類的基本結(jié)構(gòu)如下,我們給鍵值添加了一段前綴用來避免鍵值沖突,并且在值中加入數(shù)據(jù)過期時(shí)間戳以及分隔符,獲取值的時(shí)候再進(jìn)行判斷是否過期,這樣可以更靈活地管理存儲(chǔ)數(shù)據(jù)的生命周期。這里還用到了回調(diào)的方式,方便獲取數(shù)據(jù)訪問過程的具體結(jié)果,以及在必要時(shí)執(zhí)行相關(guān)操作。

/**
 * LocalStorage數(shù)據(jù)訪問類
 * @param {string} prefix Key前綴
 * @param {string} timeSplit 時(shí)間戳與存儲(chǔ)數(shù)據(jù)之間的分割符
 */
var Dao = function (prefix, timeSplit) {
    this.prefix = prefix;
    this.timeSplit = timeSplit || '|-|';
}
// LocalStorage數(shù)據(jù)訪問類原型方法
Dao.prototype = {
    // 操作狀態(tài)
    status: {
        SUCCESS: 0,     // 成功
        FAILURE: 1,     // 失敗
        OVERFLOW: 2,    // 溢出
        TIMEOUT: 3      // 過期
    },
    // 本地存儲(chǔ)對象
    storage: localStorage || window.localStorage,
    // 獲取帶前綴的真實(shí)鍵值
    getKey: function (key) {
        return this.prefix + key;
    },
    // 添加(修改)數(shù)據(jù)
    set: function (key, value, callback, time) {
       ...
    },
    // 獲取數(shù)據(jù)
    get: function (key, callback) {
        ...
    },
    // 刪除數(shù)據(jù)
    remove: function (key, callback) {
        ...
    }
}

添加(修改)數(shù)據(jù)

/**
    * 添加(修改)數(shù)據(jù)
    * @param key 數(shù)據(jù)字段標(biāo)識(shí)
    * @param value 數(shù)據(jù)值
    * @param callback 回調(diào)函數(shù)
    * @param time 過期時(shí)間
    */
    set: function (key, value, callback, time) {
        // 默認(rèn)為成功狀態(tài)
        var status = this.status.SUCCESS,
            key = this.getKey(key);
        try {
            // 獲取過期時(shí)間戳
            time = new Date(time).getTime() || time.getTime();
        } catch (e) {
            // 未設(shè)置過期時(shí)間時(shí)默認(rèn)為一個(gè)月
            time = new Date().getTime() + 1000 * 60 * 60 * 24 * 30;
        }
        try {
            // 向本地存儲(chǔ)中添加(修改)數(shù)據(jù)
            this.storage.setItem(key, time + this.timeSplit + value);
        } catch (e) {
            // 發(fā)生溢出
            status = this.status.OVERFLOW;
        }
        // 執(zhí)行回調(diào)并傳入?yún)?shù)
        callback && callback.call(this, status, key, value);
    }

獲取數(shù)據(jù)

/**
    * 獲取數(shù)據(jù)
    * @param key 數(shù)據(jù)字段標(biāo)識(shí)
    * @param callback 回調(diào)函數(shù)
    */
    get: function (key, callback) {
        var key = this.getKey(key),
            status = this.status.SUCCESS,    // 獲取數(shù)據(jù)狀態(tài)
            value = null;    // 獲取數(shù)據(jù)值

        try {
            // 從本地存儲(chǔ)獲取數(shù)據(jù)
            value = this.storage.getItem(key);
        } catch (e) {
            // 獲取數(shù)據(jù)失敗
            status = this.status.FAILURE;
            value = null;
        }

        // 如果成功獲取數(shù)據(jù)
        if (status !== this.status.FAILURE) {
            var index = value.indexOf(this.timeSplit),
                timeSplitLen = this.timeSplit.length,
                // 獲取時(shí)間戳
                time = value.slice(0, index);
            // 判斷數(shù)據(jù)是否未過期
            if (new Date(1*time).getTime() > new Date().getTime() || time == 0) {
                // 獲取數(shù)據(jù)值
                value = value.slice(index + timeSplitLen);
            } else {
                // 數(shù)據(jù)已過期,刪除數(shù)據(jù)
                value = null;
                status = this.status.TIMEOUT;
                this.remove(key);
            }
        }

        // 執(zhí)行回調(diào)
        callback && callback.call(this, status, value);
        // 返回結(jié)果值
        return value;
    }

刪除數(shù)據(jù)

/**
    * 刪除數(shù)據(jù)
    * @param key 數(shù)據(jù)字段標(biāo)識(shí)
    * @param callback 回調(diào)函數(shù)
    */
    remove: function (key, callback) {
        // 設(shè)置默認(rèn)狀態(tài)為失敗
        var status = this.status.FAILURE,
            key = this.getKey(key),
            value = null;
        try {
            // 獲取數(shù)據(jù)值
            value = this.storage.getItem(key);
        } catch (e) {
            // 數(shù)據(jù)不存在,不采取操作
        }
        // 如果數(shù)據(jù)存在
        if (value) {
            try {
                // 刪除數(shù)據(jù)
                this.storage.removeItem(key);
                status = this.status.SUCCESS;
            } catch (e) {
                // 數(shù)據(jù)刪除失敗,不采取操作
            }
        }
        // 執(zhí)行回調(diào)并傳入?yún)?shù),刪除成功則傳入被刪除的數(shù)據(jù)值
        callback && callback.call(this, status, status > 0 ? null : value.slice(value.indexOf(this.timeSplit) + this.timeSplit.length));
    }

用法

var dao = new Dao('myModule_');
// 添加/修改數(shù)據(jù)
dao.set('token', 'abc', function () { console.log(arguments); });
// 獲取數(shù)據(jù)
var value = dao.get('token', function () { console.log(arguments); });
console.log(value);
// 刪除數(shù)據(jù)
dao.remove('token', function () { console.log(arguments); });

寫在最后

其實(shí)數(shù)據(jù)訪問對象模式更適合與服務(wù)器端的數(shù)據(jù)庫操作,比如在nodejs中操作MongoDB,通過對數(shù)據(jù)庫增刪改查操作的封裝,可以方便我們對前端存儲(chǔ)的管理,不必為操作數(shù)據(jù)庫感到煩惱,DAO已經(jīng)為我們提供了便捷統(tǒng)一的接口,這樣在團(tuán)隊(duì)開發(fā)中就不用擔(dān)心影響到其他人的數(shù)據(jù)了。

本文為作者kMacro原創(chuàng),轉(zhuǎn)載請注明來源:http://www.itdecent.cn/p/ffdaa99dbde8

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容