mardi 4 août 2015

Command Pattern: Where to create the Command items?

I've used the command pattern quite extensively, and it works well. However, what's usually not discussed is where the instances of the Commands are created.

The following examples illustrate this issue: A Document has a function setText() that sets the text. Depending on whether a Command should be created, a bool withUndo could be added:

class Document {
public:
    void setText(const std::string text, bool withUndo) {
        if (withUndo) {
            commandManager()->addAndExecute(new SetTextCommand(this, text));
        } else {
            m_text = text;
        }
    }
private:
    std::string m_text;
}

Here, the SetTextCommand would execute document->setText(text, false) to perform the real work.

This interface allows both: Directly modifying the data model (withUndo == false) and modification through the Command pattern.

It is obvious that both is needed, since /somewhere/ these Commands needs to be created.

However, it is rather obvious, that this API is bad, since every function that modifies the data model needs the extra bool withUndo.

From that follows the question: How to implement this in a clean way?

PS: I have ideas myself, but I feel this must be a solved problem with good solutions.

Aucun commentaire:

Enregistrer un commentaire