21_备忘录模式

一、备忘录相关类

package com.study.memento

/**
 * 视频类,记录播放视频的名称、视频地址、当前所播放的进度
 */
class TencentVideo(var videoName: String, var videoUrl: String, var videoPlayProgress:Int){
    
    
    override fun toString(): String {
    
    
        return "TencentVideo(videoName='$videoName', videoUrl='$videoUrl', videoPlayProgress=$videoPlayProgress)"
    }
}
package com.study.memento

import java.util.*

/***
 * 视频播放的管理类
 */
object TencentVideoMananger {
    
    
    val tencentVideos = Stack<TencentVideo>()

    /**
     * 保存至备忘录
     */
    fun addMemento(tencentVideo: TencentVideo) {
    
    
        tencentVideos.push(tencentVideo)
    }

    /**
     * 从备忘录中获取
     */
    fun getMemento() = tencentVideos.pop()
}

二、主程序调用

package com.study.memento

/**
 * 备忘录模式
 * 针对对象的存储,便于用户想要找回之前的对象。
 *
 * 定义和类型
  定义:保存一个对象的某个状态,以便在适合的时候恢复对象
  “后悔药”

   类型:行为型

  适用场景
  保存及恢复数据相关业务场景
  后悔的时候,即想恢复到之前的状态

  优点
  为用户提供一种可恢复机制
  存档信息的封装

  缺点
  资源占用
 */
fun main() {
    
    
    val tencentVideo00 = TencentVideo("大江大河", "http://大江大河", 23)
    val tencentVideo01 = TencentVideo("白夜追凶", "http://白夜追凶", 33)
    val tencentVideo02 = TencentVideo("精绝古城", "http://精绝古城", 13)

    //...进行播放,随时保持记录
    TencentVideoMananger.addMemento(tencentVideo00)
    TencentVideoMananger.addMemento(tencentVideo01)
    TencentVideoMananger.addMemento(tencentVideo02)

    //...想要获取时获取
    val memento02 = TencentVideoMananger.getMemento()
    println(memento02)
    val memento01 = TencentVideoMananger.getMemento()
    println(memento01)
    val memento00 = TencentVideoMananger.getMemento()
    println(memento00)
}

三、运行结果

猜你喜欢

转载自blog.csdn.net/Duckdan/article/details/111772459