备忘录模式

title

备忘录模式(Memento Pattern)是一种行为型设计模式,用于保存对象的内部状态并在需要时恢复。它将对象状态封装在备忘录(Memento)对象中,以便可以将其保存在其他对象(如守护者对象)中。备忘录对象可以存储原始对象的状态,并且可以在需要时将其还原为原始状态。

在备忘录模式中,有三个主要角色:

  • 原始对象(Originator):需要保存状态的对象,它将状态封装在备忘录中并从备忘录中恢复状态。

  • 备忘录对象(Memento):用于存储原始对象的状态的对象,它可以包含原始对象的状态信息。

  • 守护者对象(Caretaker):用于存储备忘录对象的对象。它可以将备忘录对象传递给原始对象以恢复其状态。

以下是一个备忘录模式的简单示例代码,假设有一个游戏角色类(GameRole),其中包含了该角色的生命值、攻击力和防御力等属性。在游戏中,玩家可以对角色进行攻击、加血、加攻击力等操作。为了实现游戏的保存和恢复功能,我们使用备忘录模式来保存和恢复角色的状态。

GameRole.java:

public class GameRole {
    private int hp;
    private int attack;
    private int defense;

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

    public void attack() {
        System.out.println("角色进行攻击");
    }

    public void addHp(int hp) {
        this.hp += hp;
        System.out.println("角色生命值增加" + hp);
    }

    public void addAttack(int attack) {
        this.attack += attack;
        System.out.println("角色攻击力增加" + attack);
    }

    public void addDefense(int defense) {
        this.defense += defense;
        System.out.println("角色防御力增加" + defense);
    }

    public Memento save() {
        return new Memento(hp, attack, defense);
    }

    public void restore(Memento memento) {
        this.hp = memento.getHp();
        this.attack = memento.getAttack();
        this.defense = memento.getDefense();
    }

    public static class Memento {
        private final int hp;
        private final int attack;
        private final int defense;

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

        public int getHp() {
            return hp;
        }

        public int getAttack() {
            return attack;
        }

        public int getDefense() {
            return defense;
        }
    }

    @Override
    public String toString() {
        return "GameRole{" +
                "hp=" + hp +
                ", attack=" + attack +
                ", defense=" + defense +
                '}';
    }
}

使用备忘录模式保存 GameRole 的状态:

public class Main {
    public static void main(String[] args) {
        GameRole gameRole = new GameRole(100, 50, 30);
        List<GameRole.Memento> mementos = new ArrayList<>();
        mementos.add(gameRole.save());

        gameRole.attack();
        gameRole.addHp(20);
        mementos.add(gameRole.save());

        gameRole.addAttack(10);
        gameRole.addDefense(5);
        mementos.add(gameRole.save());

        System.out.println("当前角色状态:" + gameRole);

        // 恢复到之前的状态
        gameRole.restore(mementos.get(1));
        System.out.println("恢复到之前的状态:" + gameRole);
    }
}

运行上述代码,输出如下:

角色进行攻击
角色生命值增加20
角色攻击力增加10
角色防御力增加5
当前角色状态:GameRole{hp=120, attack=60, defense=35}
恢复到之前的状态
powered by Gitbook© 2023 编外计划 | 最后修改: 2023-11-24 03:37:01

results matching ""

    No results matching ""