Memento Pattern bất biến với Java Records

Memento Pattern cho phép ghi lại và khôi phục trạng thái nội bộ của một đối tượng mà không vi phạm nguyên tắc bao đóng (encapsulation).

Kiến trúc Memento:

Memento Design Pattern Architecture

Memento bất biến với Record

Một trong những yêu cầu quan trọng nhất của Memento là trạng thái được lưu trữ phải là bất biến (immutable) để tránh việc Caretaker vô tình chỉnh sửa. Trong Modern Java, Record là công cụ lý tưởng để định nghĩa Memento:

// Memento là một record bất biến hoàn hảo
public record EditorMemento(String content, int cursorX, int cursorY) {}

public class TextEditor {
    private String content;
    private int cursorX;
    private int cursorY;

    public EditorMemento save() {
        return new EditorMemento(content, cursorX, cursorY);
    }

    public void restore(EditorMemento memento) {
        this.content = memento.content();
        this.cursorX = memento.cursorX();
        this.cursorY = memento.cursorY();
    }
}

Không lo rò rỉ trạng thái, cú pháp khai báo cực ngắn gọn.

Bình luận (0)

Đang tải bình luận...