gpt4 book ai didi

java - 在 Java 中实现 Memento 模式的不同方法

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:13:04 24 4
gpt4 key购买 nike

我正在对 Memento Pattern 进行一些研究,似乎我遇到的大多数示例似乎都比较相似(将 String 保存到数组中并在需要时恢复它)现在如果我错了请纠正我但是我相信我刚才描述的方法是“对象克隆”,但实现纪念品模式的其他方法是什么?

据我所知,可以使用序列化,但似乎有一个灰色区域,人们说它违反了对象的封装,因此不是实现 Memento 模式的方法。

那么有人能阐明实现该模式的方法吗?我的研究提出了所有不同事物的混合体,这让一切变得困惑。

谢谢

最佳答案

Java Collections 框架定义了Queue,这可以提供帮助。

候选代码:

public final class Memento<T>
{
// List of saved values
private final Queue<T> queue = new ArrayDeque<T>();

// Last entered value, whether it has been saved or not
private T currentValue;

// No initial state, ie currentValue will be null on construction, hence
// no constructor

// Set a value, don't save it
public void set(final T value)
{
currentValue = value;
}

// Persist the currently saved value
public void persist()
{
queue.add(currentValue);
}

// Return the last saved value
public T lastSaved()
{
return queue.element();
}

// Return the last entered value
public T lastEntered()
{
return currentValue;
}
}

值得注意的是,这段代码中缺少很多东西,但很容易实现:

  • 恢复到上次保存的值;
  • 不检查空值;
  • T 没有实现Serializable
  • 便捷方法(例如,添加一个值并使其成为最后保存的状态);
  • 代码不是线程安全的!

等等

示例代码:

public static void main(final String... args)
{
final Memento<String> memento = new Memento<String>();

memento.set("state1");
System.out.println(memento.lastEntered()); // "state1"
memento.persist();
memento.set("state2");
System.out.println(memento.lastEntered()); // "state2"
System.out.println(memento.lastSaved()); // "state1"
}

实际上:这是一个脑残的实现,可以改进,但可以用作基础——扩展它取决于您的需要;)

关于java - 在 Java 中实现 Memento 模式的不同方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14082892/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com