Java document state pattern?

I'm new to Java programming and I would like to know if there is some common practice of managing the state of an open document (the current state is saved or dirty), saving a document, opening, creating a new document, etc. How did you approach this?

Right now I have a small Swing application and have actions to open and close a document and create a new one, but I don't know how to control if the user has saved the file or not (I need this to check if the user wants to create a new one or open an existing one when work with the current one.)

Is there some kind of template for this? All advice is highly appreciated as I am still learning to swim with Java.

+2


source to share


3 answers


As far as I know, Swing has no document state management mechanisms. You have to do it yourself. But then there isn't much code that needs to be written, and if you have several different documents in your application, you can put that stuff in an abstract base class.

The basic approach has already been described: just include the dirty flag in your document data structure. You should consider writing down which of your operations, such as "create", "open", "save", "close", modify and evaluate this flag. I would suggest a state diagram (not necessarily a UML state machine variant ) as a tool to indicate this.



If you need more complex functionality, especially undo / redo, take a look at the Memento pattern . Most of the code that needs to be written when using this pattern is specific to the application and its data structures (that is, the types you create to manipulate documents), so it would be difficult to effectively generalize this and incorporate it into a framework like Swing or RCP.

+3


source


You have a boolean variable named isDirty that starts with false.

Every time a change is made to the document, it is set to true in the code.

All other program functions (Open, save, new menus, etc) check the status of this boolean before doing anything else.



So they also represent familiar dialogs: are you sure you want to exit, Discard your changes etc

I have used this multiple times in the real world of Swing Apps

+2


source


You might consider working with temporary versions of your document (i.e. you open the main document, but when you edit it, a temporary document is created). In this case, another user who opens the same document will see the original document. As far as I know, this is a common practice.

But I'm not sure if you want to support such complex behavior.

0


source







All Articles