# 数据访问对象模式(DAO)

  1. 定义:主要用来抽象和封装一个对象来对数据源进行访问和存储,这样可以方便对数据的管理,避免数据间的重复,覆盖等问题
  2. 例子:
// {
//     nameSpace|key:expire|value
// }
var DataVisitor = function(nameSpace, splitSign) {
  this.nameSpace = nameSpace;
  this.splitSign = splitSign || "|";
};
DataVisitor.prototype = {
  status: {
    SUCCESS: 0,
    FAILURE: 1,
    OVERFLOWER: 2,
    TIMEOUT: 3,
  },
  getKey: function(key) {
    return this.nameSpace + this.splitSign + key;
  },
  set: function(key, value, cbFn, expireTime) {
    var status = this.status.SUCCESS;
    key = this.getKey(key);
    expireTime =
      typeof expireTime === "number" ? expireTime + new Date().getTime() : -1;
    try {
      window.localStorage.setItem(key, expireTime + this.splitSign + value);
    } catch (e) {
      status = this.status.OVERFLOWER;
    }
    cbFn && cbFn.call(this, status, key, value);
    return value;
  },
  get: function(key, cbFn) {
    key = this.getKey(key);
    var status = this.status.SUCCESS;
    var value = window.localStorage.getItem(key);
    if (value) {
      var index = value.indexOf(this.splitSign),
        time = value.slice(0, index);
      if (time > new Date().getTime() || time == -1) {
        value = value.slice(index + this.splitSign.length);
      } else {
        value = null;
        status = this.status.removeItem(key);
      }
    } else {
      status = this.status.FAILURE;
    }
    cbFn && cbFn.call(this, status, key, value);
    return value;
  },
  removeItem: function(key, cbFn) {
    var status = this.status.FAILURE;
    key = this.getKey(key);
    value = window.localStorage.getItem(key);
    if (value) {
      value.slice(value.indexOf(this.splitSign) + this.splitSign.length);
      window.localStorage.removeItem(key);
      status = this.status.SUCCESS;
    }
    cbFn && cbFn.call(this, status, key, value);
  },
};
var lenrnInPro = new DataVisitor("learnInfo");
// lenrnInPro.set('aaa', '123', function (status, key, value) {
//     console.log(status, key, value);
// })
// lenrnInPro.get('aaa', function (status, key, value) {
//     console.log(status, key, value);
// })
// lenrnInPro.remove('aaa', function (status, key, value) {
//     console.log(status, key, value);
// })
lenrnInPro.set(
  "aaa",
  "123",
  function(status, key, value) {
    console.log(status, key, value);
  },
  1000 * 2
);
lenrnInPro.get("aaa", function(status, key, value) {
  console.log(status, key, value);
});
setTimeout(function() {
  lenrnInPro.set(
    "aaa",
    function(status, key, value) {
      console.log(status, key, value);
    },
    1000 * 3
  );
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91