1. 程式人生 > 其它 >設計模式-23種設計模式-行為型-備忘錄模式

設計模式-23種設計模式-行為型-備忘錄模式

一、備忘錄模式介紹

二、備忘錄模式引入

需求:

UML類圖:

程式碼實現(Java):

public class Memento {

    //攻擊力
    private int vit;
    //防禦力
    private int def;
    public Memento(int vit, int def) {
        super();
        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; } }
import java.util.ArrayList;
import java.util.HashMap;

//守護者物件, 儲存遊戲角色的狀態
public class Caretaker {

    //如果只儲存一次狀態
    private
Memento memento; //對GameRole 儲存多次狀態 //private ArrayList<Memento> mementos; //對多個遊戲角色儲存多個狀態 //private HashMap<String, ArrayList<Memento>> rolesMementos; public Memento getMemento() { return memento; } public void setMemento(Memento memento) { this
.memento = memento; } }
public class GameRole {

    private int vit;
    private int def;

    //建立Memento ,即根據當前的狀態得到Memento
    public Memento createMemento() {
        return new Memento(vit, def);
    }

    //從備忘錄物件,恢復GameRole的狀態
    public void recoverGameRoleFromMemento(Memento memento) {
        this.vit = memento.getVit();
        this.def = memento.getDef();
    }

    //顯示當前遊戲角色的狀態
    public void display() {
        System.out.println("遊戲角色當前的攻擊力:" + this.vit + " 防禦力: " + this.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;
    }

}
public class Client {

    public static void main(String[] args) {
        //建立遊戲角色
        GameRole gameRole = new GameRole();
        gameRole.setVit(100);
        gameRole.setDef(100);

        System.out.println("和boss大戰前的狀態");
        gameRole.display();

        //把當前狀態儲存caretaker
        Caretaker caretaker = new Caretaker();
        caretaker.setMemento(gameRole.createMemento());

        System.out.println("和boss大戰~~~");
        gameRole.setDef(30);
        gameRole.setVit(30);

        gameRole.display();

        System.out.println("大戰後,使用備忘錄物件恢復到站前");

        gameRole.recoverGameRoleFromMemento(caretaker.getMemento());
        System.out.println("恢復後的狀態");
        gameRole.display();
    }

}

三、備忘錄模式注意事項和細節