I'm trying to create one instance of a file type (txt, jpg, doc, etc...). I have an inheritance structure that goes something like this.
abstract FileClass <- superclass
JPG DOC TXT <- (child classes)
Ignore the fact that this example doesn't seem very practical, it's more for just learning inheritance. I have a swing menu where I can select to load, or save any of these child classes.
If I load up a JPG file I want to keep track of the files name, size, and keep a File object of it. If I then click on the DOC menu and select save, I want it be able to use the file object that was created when I loaded the JPG file.
In my menu class I have a reference to the FileClass (superclass), and have methods for each menu operation (a load/save method for each subclass). The problem is each menu option creates a new subclass object with a superclass reference. So it creates a new object each time a menu option is selected, which means I lose all the information of a loaded file if I choose to save it.
[ September 23, 2006: Message edited by: Bob Zoloman ]
When you're implementing an editor like this, typically each open document would be represented by an object of some kind. That object would be the "go-to object" for everything concerning that document. It would keep track of the data, the components used to display the document, etc. The application itself would keep track of a list of these document objects -- i.e., when the menus created one, they would add the object they created to that list. Then when the menu was asked to save a document, it would ask the application for the appropriate document object (i.e., the one that owns the component that's showing, let's say) and call save() on that.
So the thing you want to add to your "open" code is something like
where "registerNewDocument" adds the argument to a List for later reference.
Originally posted by Bob Zoloman: Would that be like implementing an observer pattern?
That's not what I have in mind, no. All I'm saying is that the object you create in your "Open" menu item should be saved someplace, so that later, you can call save() on it. You want to make a new object each time you pick "Open", as each object represents a document, and Open creates a new document.