zoukankan      html  css  js  c++  java
  • 备忘录实现+具体需求应用备忘录

    首先你要了解设计模式,了解备忘录模式,如果不了解那就先去了解吧.
    class Cache { // 中间对象
    constructor(json) {
    this.json = json
    }
    getJson() {
    return this.json
    }
    }
    class CacheList { // 缓存列表
    constructor() {
    this.list = []
    }
    add(cache) {
    this.list.push(cache)
    }
    get(index) {
    return this.list[index]
    }
    }
    class CurDagJson { // 当前json处理
    constructor() {
    this.dagJson = null
    }
    setCurJson(dagJson){
    this.dagJson = dagJson
    }
    getCurJson(){
    return this.dagJson
    }
    setCacheCurJson(dagJson) {
    this.dagJson = dagJson
    return new Cache(this.dagJson)
    }
    getCacheCurJson(cache) {
    this.dagJson = cache.getJson()
    }
    }
    const curdagjson = new CurDagJson()
    const cachelist = new CacheList()
    const goodBox = {
    'curdagjson': curdagjson,
    'cachelist': cachelist
    }
    export default goodBox
    但是再具体的实现中我选择了一种简单的方法,也许不叫备忘录模式,但实现了和备忘录模式一样的功能
     
    class Cache {
    constructor() {
    this.history = new Map()
    this.pointer = -1
    }
    getPointer() {
    return this.pointer
    }
    set(record) {
    this.pointer++
    this.history.set(this.pointer, record)
    return this
    }
    get(pointer) {
    return this.history.get(this.pointer)
    }
    next() {
    this.pointer++
    return this.history.get(this.pointer)
    }

    prev() {
    if (this.pointer == 0) return
    this.pointer--
    return this.history.get(this.pointer)
    }
    cover(index, size) {
    var arr = [...this.history]
    arr = arr.splice(0, index + 1)
    this.history = new Map(arr)
    this.pointer = index
    return this
    }
    }
    export default Cache

    上面就是我具体实现,我给数据分了类,

    !!!!!!!!!! 
     
    为什么要分类呢?因为数据很多,我们不可能去向map里存那么大的数据,就算是存,也不会存很多步.
    那么我的需求就是可以返回20步,数据大怎么办,所以我给数据分类,你可以理解为把存进去的数据分了类
    {id:10001,type:add,action:del,oldJson:''}
    id当然代表了你操作数据的唯一标识,比如我的type是添加,那么可以想到,他肯定是做了添加的操作,所以返回的action动作就是del,至于为什么要有oldJson呢?
    如果操作是更新,我们就要记录旧的数据,oldJson就是将旧的数据存起来,存你改变的,而不是存所有.当然视情况而定
     
     
     
     
     
     
     
  • 相关阅读:
    js对象的sessionStorage,判断对象相等,判断是否包含某属性
    vant-ui的van-area使用
    JavaScript返回格式化的时间字符串
    vant-ui的van-uploader上传图片
    移动端vue页面禁止移动/滚动
    vue项目中的跨域源请求拦截问题CORS头缺少'Access-Control-Allow-Origin'
    项目开发过程中踩坑和填坑
    周报
    构建一个最简单的react程序
    Socket实现简易“多人聊天室”
  • 原文地址:https://www.cnblogs.com/MDGE/p/11405858.html
Copyright © 2011-2022 走看看