简体   繁体   中英

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:

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? What if the code of execute() is not trivial? How can I avoid code duplication in ShapeEditor and 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. 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. See how it's done in Qt .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM