备忘录模式

定义

备忘录模式(MementoPattern)在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这 个状态。这样以后就可将该对象恢复到原先保存的状态。备忘录模式属于行为型模式。

实现

public class Memento {
    int attack;
    int defend;

    public Memento(int attack, int defend) {
        this.attack = attack;
        this.defend = defend;
    }
}

class Caretaker{
    Memento memento;

    public Caretaker(Memento memento) {
        this.memento = memento;
    }

    public Memento getMemento() {
        return memento;
    }

    public void setMemento(Memento memento) {
        this.memento = memento;
    }
}

class GameRole{

    int attack;
    int defend;

    public GameRole(int attack, int defend) {
        this.attack = attack;
        this.defend = defend;
    }

    public Memento creatMemento(){
        return new Memento(attack,defend);
    }

    public int getAttack() {
        return attack;
    }

    public void setAttack(int attack) {
        this.attack = attack;
    }

    public int getDefend() {
        return defend;
    }

    public void setDefend(int defend) {
        this.defend = defend;
    }

    public void display(){
        System.out.println("攻击力:"+attack+" 防御力:"+defend);
    }

    public void recover(Memento memento){
        this.attack = memento.attack;
        this.defend = memento.defend;
    }
}

class TestMemento{
    public static void main(String[] args) {
        GameRole gameRole = new GameRole(100, 100);
        //备份
        Memento memento = gameRole.creatMemento();
        Caretaker caretaker = new Caretaker(memento);
        System.out.println("战斗结束以后");
        gameRole.setAttack(30);
        gameRole.setDefend(30);
        System.out.println("恢复");
        gameRole.recover(caretaker.getMemento());
        gameRole.display();
    }

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值