Java 设计模式之备忘录模式

备忘录模式(Memento)

在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态,这样以后就可将该对象恢复到原先保存的状态。
在这里插入图片描述

在这里插入图片描述

在这里插入图片描述
游戏角色:

//游戏角色
public class Actor {
    //生命力
    private int vit;
    //攻击力
    private int atk;
    //防御力
    private int def;

    public Actor(int vit, int atk, int def) {
        this.vit = vit;
        this.atk = atk;
        this.def = def;
    }
    //存储备忘录
    public Memento creatMemento(){
        return new Memento(this.vit,this.atk,this.def);
    }
    //得到备忘录,恢复数据
    public void getMemento(Memento memento){
        this.vit = memento.getVit();
        this.atk = memento.getAtk();
        this.def = memento.getDef();
    }
    @Override
    public String toString() {
        return "Actor{" +
                "vit=" + vit +
                ", atk=" + atk +
                ", def=" + def +
                '}';
    }
    //打Boss受伤
    public void attack(){
        this.vit = 0;
        this.def = 0;
        this.atk = 0;
    }
}

备忘录:

//备忘录
public class Memento {
    //生命力
    private int vit;
    //攻击力
    private int atk;
    //防御力
    private int def;

    public Memento(int vit, int atk, int def) {
        this.vit = vit;
        this.atk = atk;
        this.def = def;
    }

    public int getVit() {
        return vit;
    }

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

    public int getAtk() {
        return atk;
    }

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

    public int getDef() {
        return def;
    }

    public void setDef(int def) {
        this.def = def;
    }
}

管理者:

//备忘录管理者
public class MementoCareTaker {
    private Memento memento;

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

    public Memento getMemento() {
        return memento;
    }

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

测试:

public class Test {
    public static void main(String[] args) {
        //初始化
        Actor actor = new Actor(100, 100, 100);
        System.out.println(actor.toString());
        //保存
        MementoCareTaker mementoCareTaker = new MementoCareTaker(actor.creatMemento());
        //打Boss
        actor.attack();
        System.out.println(actor.toString());
        //恢复
        actor.getMemento(mementoCareTaker.getMemento());
        System.out.println(actor.toString());
    }
}
Actor{vit=100, atk=100, def=100}
Actor{vit=0, atk=0, def=0}
Actor{vit=100, atk=100, def=100}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值