设计模式--备忘录模式

1 将对象信息保存起来,可以以后将该对象恢复在保存之前的状态。
这里写图片描述
被保存的类:

public class GameRole {

    // 攻击力
    public Integer aggressivity;

    // 防御力
    public Integer defensive;

    public GameRole(Integer aggressivity, Integer defensive) {
        this.aggressivity = aggressivity;
        this.defensive = defensive;
    }

    // 改变状态
    public void fight() {
        this.aggressivity = 0;
        this.defensive = 0;
    }

    public RoleStateMemento saveState() {
        return new RoleStateMemento(this.aggressivity, this.defensive);
    }

    public void recoveryState(RoleStateMemento roleStateMemento) {
        this.aggressivity = roleStateMemento.getGameRole().aggressivity;
        this.defensive = roleStateMemento.getGameRole().defensive;
    }

    public void displayer() {
        System.out.println(aggressivity + "           " + defensive);
    }
}

信息存储箱

public class RoleStateMemento {

    private GameRole gameRole;

    public RoleStateMemento(Integer aggressivity, Integer defensive) {
        gameRole = new GameRole(aggressivity, defensive);
    }

    public GameRole getGameRole() {
        return gameRole;
    }

    public void setGameRole(GameRole gameRole) {
        this.gameRole = gameRole;
    }
}

信息管理者

public class RoleStateCareTaker {

    private RoleStateMemento roleStateMemento;

    public RoleStateMemento getRoleStateMemento() {
        return roleStateMemento;
    }

    public void setRoleStateMemento(RoleStateMemento roleStateMemento) {
        this.roleStateMemento = roleStateMemento;
    }
}

测试:

public class TextMain {

    public static void main(String[] args) {
        GameRole gameRole = new GameRole(10, 10);

        RoleStateCareTaker roleStateCareTaker = new RoleStateCareTaker();
        RoleStateMemento roleStateMemento = gameRole.saveState();
        roleStateCareTaker.setRoleStateMemento(roleStateMemento);

        gameRole.displayer();

        gameRole.fight();// 状态改变
        gameRole.displayer();

        gameRole.recoveryState(roleStateCareTaker.getRoleStateMemento());
        gameRole.displayer();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值