[英]Command pattern: how can I do continuous actions? (e.g. moving an object)
Suppose that I'm making a program where user can draw and then move shapes around. 假设我正在编写一个程序,用户可以在其中绘制然后移动形状。
MoveCommand
then can look something like this: 然后,
MoveCommand
可能如下所示:
class MoveCommand {
public:
MoveCommand(Shape& shape, const Vector2f& offset) :
shape(shape), offset(offset)
{ }
void execute() {
shape.move(offset);
}
void undo() {
shape.move(-offset);
}
private:
Shape& shape;
Vector2f offset;
};
This works well, but how can I display preview of movement (when user holds mouse button) and then only store final offset on mouse button release? 这很好用,但是如何显示运动预览(当用户按住鼠标按钮时),然后仅在释放鼠标按钮时存储最终偏移量?
Should ShapeEditor
class move the shape and then create MoveCommand
on button release? ShapeEditor
类是否应该移动形状,然后在释放按钮时创建MoveCommand
? What if the code of execute()
is not trivial? 如果
execute()
的代码不简单怎么办? How can I avoid code duplication in ShapeEditor
and MoveCommand
? 如何避免
ShapeEditor
和MoveCommand
代码重复?
This works well, but how can I display preview of movement (when user holds mouse button) and then only store final offset on mouse button release?
这很好用,但是如何显示运动预览(当用户按住鼠标按钮时),然后仅在释放鼠标按钮时存储最终偏移量?
If I understand you correctly, you want to make the whole movement un-doable / re-doable as a single operation, while animating each individual micro-movement when it's done interactively the first time. 如果我对您的理解正确,那么您想使整个运动无法执行/只能重新执行,同时在首次交互完成时为每个微动动动画。
One way to do it is what you suggest yourself, that is recording the undo / redo command only when the movement is complete. 一种解决方法是您自己建议,即仅在移动完成后才记录undo / redo命令。 As you point out, that leads to some code duplication.
如您所指出,这会导致某些代码重复。 In practice that's not a problem, as you can always factor that common code out.
实际上,这不是问题,因为您可以随时将这些通用代码排除在外。
Another way is to create a MoveCommand for every micro-movement and then implement command merging as part of your undo / redo stack. 另一种方法是为每个微动创建一个MoveCommand,然后将命令合并作为撤消/重做堆栈的一部分。 See how it's done in Qt .
查看如何在Qt中完成 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.