views:

76

answers:

1

Hi,

I'm looking for a VBA implementation of the Memento pattern (GoF). I'm looking at converting the Java version from Wikipedia. It will be used for Undo/Redo functionality for an Excel add-in.

Specifically, I am having difficulty with the line:

return new Memento(state);

Or, to make it more specific, can someone rewrite this in VBA:

public Memento saveToMemento() {
    //System.out.println("Originator: Saving to Memento.");
    return new Memento(state);
}

The entire code that I am trying to convert is available at the Wikipedia link above.

Thanks

+1  A: 

The return keyword in Java is very different to the return keyword in VBA. In VBA, return is paired with gosub as a way of altering the flow of execution within a procedure.

In Java, return means "exit from function" and either returns a value of an appropriate type (as in your example) or returns nothing (in the case of a void function - Java equivalent of Sub in VBA).

In your example, it is going to return an object of type Memento. This must be either the return type of the function or a subtype of that return type. A new object is created through use of the new keyword (similar to the new keyword in VBA). The object called state is passed to the constructor of the new object as a parameter.

In VBA you could write this:

Function saveToMemento(state As String) As Variant

saveToMemento = createMemento(state)

End Function

where createMemento is a function you have written to create an appropriate structure to hold the memento information

barrowc
barrowc, How do I create the constructor of the new object (as parameter), or more specifically, how to write the createMemento function so that it emulates the Java code for saveToMemento?
MrSpreadsheet
You can define classes in VBA and then create objects of those classes. VBA doesn't have constructors as such but you can use `Class_Initialize()` to initialize the object. Unfortunately you can't pass parameters to that `Sub` so you would have to call a separate `Sub` to deal with setting the initial state. You might get some ideas from http://msdn.microsoft.com/en-us/library/aa227509%28VS.60%29.aspx
barrowc
Thank you, your answers were very useful.
MrSpreadsheet