Java设计模式 备忘录模式

备忘录模式

开发中常见的应用场景:
​ – 棋类游戏中的,悔棋
​ – 普通软件中的,撤销操作
​ – 数据库软件中的,事务管理中的,回滚操作
​ – Photoshop软件中的,历史记录

结构:
​ – 源发器类Originator
​ – 备忘录类Memento
​ – 负责人类CareTaker

在这里插入图片描述

Stack 常用方法

方法名描述
empty判断堆栈是否为空
pop向堆栈里面压入一个数据
push向堆栈压入一个数据
size返回当前堆栈长度(即内部数据个数)
top得到堆栈栈顶数据

实现 code

元数据类

package com.znsd.javase.meomory;

public class GameRole {

	private Integer vit;// 体力
	private Integer atk;// 攻击力

	public GameRole() {
		this.vit = 100;
		this.atk = 100;
	}

	public void show() {
		System.out.println("{体力: " + vit + ", 攻击力: " + atk + "}");
	}
	
	public void fightBoss(Integer vit, Integer atk) {
		this.vit = vit;
		this.atk = atk;
	}
	
	// ctrl + s
	public RoleStateMemento saveMemento(){
        return (new RoleStateMemento(vit, atk));
    }
    
	// ctrl + z
    public void recove(RoleStateMemento roleStateMemento){
        this.vit=roleStateMemento.getVit();
        this.atk=roleStateMemento.getAtk();
    }

}

备忘录类

public class RoleStateMemento {

	private Integer vit;// 备忘录保存的 : 体力
	private Integer atk;// 备忘录保存的 : 攻击力

	public RoleStateMemento(Integer vit, Integer atk) {
		super();
		this.vit = vit;
		this.atk = atk;
	}

	public Integer getVit() {
		return vit;
	}

	public void setVit(Integer vit) {
		this.vit = vit;
	}

	public Integer getAtk() {
		return atk;
	}

	public void setAtk(Integer atk) {
		this.atk = atk;
	}

	public void show() {
		System.out.println("{体力: " + vit + ", 攻击力: " + atk + "}");
	}

}

负责人类

public class RoleStateMange {

	private Stack<RoleStateMemento> stack = new Stack<>();

	public RoleStateMemento popMemento() {
		return stack.pop();
	}

	public RoleStateMemento pushMemento(RoleStateMemento memento) {
		return stack.push(memento);
	}

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值