Java Magazine, May/June 2018
ORACLE COM JAVAMAGAZINE MAY JUNE 2018 20 design patterns An Undo Stack Example Ive shown that one use of the Command pattern is packaging Java code to tell a remote process what to do A diferent use would be the undo stack in an editor or word processor When you request an operation such as insert move or delete the editor program could create a Command object representing the operation to be performed This object would then be passed to a perform method in the editor and upon successful completion it would be added to the undo stack The stack could be implemented as a simple push down stack of objects of the EditorCommand type When you request an undo operation the top element is popped of the stack and it is passed to an unperform method in the editor which removes the inserted text if the operation was an insertion reinserts the deleted text if the operation was a deletion and so on In a full implementation you wouldnt actually pop the undoable action and drop it after use you would keep it there for use by a redo command In adding base undo functionality into a simple line editor called edj also on my GitHub site I took a slightly simpler approach To provide a degree of separation between the main code and the model here the in memory bufer handling code I built the editor from the start with an interface called BufferPrims between the main code and the operations on the buffer These are primitive operations such as add lines delete lines and so on There are two versions of the code BufferPrimsNoUndo and BufferPrimsWithUndo In real life you probably dont need these so you might not even need the interface but having them both makes it easier to compare them to see all the changes In the first version of the code there was no undo operation So the first step was refactoring to include the undo capability in the interface and then have the no undo implementation shown next just print a message public interface BufferPrims void addLines int start List String newLines void deleteLines int start int end Print one or more lines void printLines int i int j
You must have JavaScript enabled to view digital editions.