Java Reference
In-Depth Information
State
Inner classes are most appropriate for States. They are very closely coupled with their enclosing class and have
direct access to its attributes. The following example shows how this works in practice.
A standard feature of applications is that they only save files when necessary: when changes have been made.
When changes have been made but a file has not been saved, its state is referred to as
dirty.
The content might be
different from the persistent, saved version. When the file has been saved and no further changes have been made,
the content is considered
clean.
For a clean state, the content and the file will be identical if no one else edits the
file.
This example shows the State pattern being used to update
Appointments
for the PIM, saving them to a file as necessary.
Figure A.1. State transition diagram for a file
Two states (
CleanState
and
DirtyState
) implement the
State
interface. The states are responsible for
determining the next state, which in this case is reasonably easy, as there are only two.
The
State
interface defines two methods,
save
and
edit
. These methods are called by the
CalendarEditor
when appropriate.
Example A.97
State.java
1. public interface State{
2. public void save();
3. public void edit();
4. }
The
CalendarEditor
class manages a collection of
Appointment
objects.
Example A.98
CalendarEditor.java
1. import java.io.File;
2. import java.util.ArrayList;
3. public class CalendarEditor{
4. private State currentState;
5. private File appointmentFile;
6. private ArrayList appointments = new ArrayList();
7. private static final String DEFAULT_APPOINTMENT_FILE = "appointments.ser";
8.
9. public CalendarEditor(){
10. this(DEFAULT_APPOINTMENT_FILE);
11. }
12. public CalendarEditor(String appointmentFileName){
13. appointmentFile = new File(appointmentFileName);
14. try{
15. appointments = (ArrayList)FileLoader.loadData(appointmentFile);
16. }
17. catch (ClassCastException exc){
18. System.err.println("Unable to load information. The file does not contain a list
of appointments.");