• 备忘录实现+具体需求应用备忘录


    首先你要了解设计模式,了解备忘录模式,如果不了解那就先去了解吧.
    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就是将旧的数据存起来,存你改变的,而不是存所有.当然视情况而定
     
     
     
     
     
     
     
  • 相关阅读:
    图论--曼哈顿距离最小生成树模板
    图论--生成树计数模板
    图论--欧拉回路--弗罗莱算法模板
    Codeforce 1255 Round #601 (Div. 2)D. Feeding Chicken (模拟)
    pta 习题集5-17 家谱处理
    pta习题集5-16 地下迷宫探索
    pta 习题集5-17 哥尼斯堡的“七桥问题”
    pta习题集5-16 朋友圈
    pta 习题集5-19 列车厢调度
    pta 习题集5-18 打印学生选课清单
  • 原文地址:https://www.cnblogs.com/MDGE/p/11405858.html
Copyright © 2020-2023  润新知