java-备忘录模式案例

题目:

使用备忘录模式实现游戏中存档的功能。存档的属性包括血量、攻击力、防御力三种。

类图:

代码:

package Memento;

class RoleStateMemento
{
    private int vit;
    private int atk;
    private int def;

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

    public void setVit(int vit){ this.vit = vit; }
    public int getVit(){ return this.vit; }
    public void setAtk(int atk){ this.atk = atk; }
    public int getAtk(){ return this.atk; }
    public void setDef(int def){ this.def = def; }
    public int getDef(){ return this.def; }
};

class GameRole
{
    private int vit;
    private int atk;
    private int def;
    public void initState()
    {
        this.vit = 1000;
        this.atk = 100;
        this.def = 100;
    }
    public void setVit(int vit){ this.vit = vit; }
    public int getVit(){ return this.vit; }
    public void setAtk(int atk){ this.atk = atk; }
    public int getAtk(){ return this.atk; }
    public void setDef(int def){ this.def = def; }
    public int getDef(){ return this.def; }
    public void stateDisplay()
    {
        System.out.println("角色当前状态:");
        System.out.println("生命值:" + this.vit);
        System.out.println("攻击力:" + this.atk);
        System.out.println("防御力:" + this.def);
    }

    public RoleStateMemento saveState()
    {
        return new RoleStateMemento(this.vit, this.atk, this.def);
    }

    public void recoveryState(RoleStateMemento  memento)
    {
        this.vit = memento.getVit();
        this.atk = memento.getAtk();
        this.def = memento.getDef();
    }
};

class RoleStateCarataker
{
    private RoleStateMemento memento;
    public void setRoleStateMemento(RoleStateMemento memento){ this.memento = memento; }
    public RoleStateMemento getRoleStateMemento(){ return this.memento; }
};

public class GameSave {
    public static void main(String[] args){
        System.out.println("打BOSS前存档" );
        GameRole gr = new GameRole();
        gr.initState();
        gr.stateDisplay();

        RoleStateCarataker stateAdmin = new RoleStateCarataker();
        stateAdmin.setRoleStateMemento(gr.saveState());

        gr.setVit(0);
        System.out.println("打BOSS前存档" );
        gr.stateDisplay();

        gr.recoveryState(stateAdmin.getRoleStateMemento());
        System.out.println("读取档案重新开始" );
        gr.stateDisplay();        
    }
}

结果:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值