Java Magazine, May/June 2018
ORACLE COM JAVAMAGAZINE MAY JUNE 2018 26 design patterns There isnt room to dissect it here but if you want to look at its code check out this GitHub repository In the before version a Document Listener was attached to the main and only document so that when the TextArea made any changes to the model Id be notified and an unsavedChanges boolean would be set to prompt for unsaved changes when exiting In the after version I use Swings UndoableEditListener and UndoManager To see how all those pieces fit together look at the code starting at Set up Undo Redo actions and the Command objects UndoAction and RedoAction The GoF book says this A command can have a wide range of abilities At one extreme it merely defines a binding between a receiver and the actions that carry out the request At the other extreme it implements everything itself without delegating to a receiver at all in between are commands that have enough knowledge to find their receiver dynamically In bidpay the command has an explicit receiver and is little more than that binding In edj theres only one source file so the document is available to all code and does not need to be passed with the command In TinyPad the command when coupled with the undo manager is smart enough to know its associated document internally Conclusion The Command pattern isnt just for undo stacks of course Its good for remote execution as you saw in my first example and for journaling in database like systems and file systems to be re executed after a crash A composite version can be used to implement database style transactions and batch processing The Command pattern is a good example of a general purpose design pattern that has many uses and when applied properly it will clarify your code and make it more readable and maintainable And thats largely what this patterns business is all about article Ian Darwin @ Ian_ Darwin has done all kinds of things from developing mainframe applications and desktop publishing applications for UNIX and Windows to a desktop database application in Java to healthcare apps in Java for Android Hes the author of Java Cookbook and Android Cookbook both from OReilly He has also written a few courses and taught many at Learning Tree International
You must have JavaScript enabled to view digital editions.