在 Java 中实现状态更改的撤消
我开始实现命令模式,希望得到一个有用的解决方案来解决我提供撤消操作的问题。现在我面临一个问题:
在涉及操作时实现撤消相当简单:当我将 5 添加到一个数字时,然后我减去 5。当我将一个对象添加到列表中时,然后我将其删除,等等在。但是如果我有一个完整的状态而不是列表之类的东西怎么办?
一个例子:我对类中线程的信息进行建模:
public class ThreadInfo implements Comparable<ThreadInfo> {
final int id;
String name;
int priority;
String state;
int waitCount;
// ...
}
某些信息不会改变,例如 id。如上所述,撤消 waitCount 很容易,只需减去即可。但是优先级
或状态
又如何呢?目前尚不清楚如何撤消这些信息。
我想到的唯一想法是:在初始化命令对象时,保留其对象中的旧状态:通过将相关数据传递到构造函数中:
public MyCommand(int priority, String state) {
previousPriority = priority;
previousState = state;
}
或者最好让 ThreadInfo 有一个列表国家和优先事项是当前的首要要素吗?
I am starting to implementing the command pattern in the hope to get a useful solution to my problem of providing an undo operation. Now I am facing a certain issue:
Implementing undo when operations are involved are rather easy: when I've added 5 to a number then I subtract 5. When I've added an object to a list, then I remove it, and so on. But what if I have a total state and not something like a list?
An example: I model information about a thread in a class:
public class ThreadInfo implements Comparable<ThreadInfo> {
final int id;
String name;
int priority;
String state;
int waitCount;
// ...
}
Certain information does not change, for instance the id. Undoing the waitCount
is easy as described above, just subtract. But what about priority
or state
? It is not clear how to undo these information.
The only idea I came up with: when initializing the command object, preserve the old state in it's object: by passing the relevant data into the constructor:
public MyCommand(int priority, String state) {
previousPriority = priority;
previousState = state;
}
Or would it be better to let ThreadInfo
have a list of states and priorities with being the first elements the current?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
只需保持旧状态即可。例如
Just hold old state in command. for example
我会选择第一个解决方案:保存状态的 MyCommand 构造函数。它很简单并且应该可以工作。对于更通用的撤消/重做方法,请查看备忘录模式。您可以将它与基于命令的方法结合起来。
I would go for the first solution: MyCommand constructor which saves the state. It is simple and should work. For a more general undo/redo approach, have a look at the memento pattern. You can probably combine it with your command based approach.
Java 已经支持撤消/重做操作。看看这个教程。
您可以扩展 AbstractUndoableEdit 类来定义对象上撤消/重做操作的语义。
Java already have support for undo/redo operations. Have a look a this tutorial.
You can extends AbstractUndoableEdit class to define the semantic of undo/redo operations on your objects.
最好在命令方法中保留旧对象的备份。
我已经使用过这种方法。
It's better to have a Backup of the old object in side your comand method.
I already used this type of approach .