【设计模式】备忘录模式

给用户提供了一种可以恢复状态的机制,可以使用户方便的回到某个历史状态,本质是在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存该状态。
package com.depthmind.designpattern;

import java.util.ArrayList;
import java.util.List;

public class MementoPattern {
    public static void main(String[] args) {
        MPlayer player = new MPlayer(100, 100);
        player.display();
        //保存玩家状态
        Memento memento = player.createMemento();
        MementoUtil.addMemento(memento);
        //玩家状态改变
        player.setVit(60);
        player.setDef(50);
        //保存改变后的状态
        Memento memento1 = player.createMemento();
        MementoUtil.addMemento(memento1);
        player.display();
        //恢复到初始状态
        player.recoverMemento(MementoUtil.getMemento(0));
        System.out.println("已恢复到初始状态!");
        player.display();
    }
}

//备忘录类
//用来保存对象状态的对象
class Memento {
    private int vit;
    private int def;

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

    public int getVit() {
        return vit;
    }

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

    public int getDef() {
        return def;
    }

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

class MementoUtil {
    private static List<Memento> mementoList = new ArrayList<>(8);

    public static void addMemento(Memento memento) {
        mementoList.add(memento);
    }

    public static Memento getMemento(int index) {
        return mementoList.get(index);
    }
}

class MPlayer {
    private int vit;
    private int def;

    public Memento createMemento() {
        return new Memento(vit, def);
    }

    public void recoverMemento(Memento memento) {
        this.vit = memento.getVit();
        this.def = memento.getDef();
    }

    public void display() {
        System.out.println("当前状态:");
        System.out.println("战斗力:" + this.vit + ",防御力:" + this.def);
    }

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

    public int getVit() {
        return vit;
    }

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

    public int getDef() {
        return def;
    }

    public void setDef(int def) {
        this.def = def;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值