Java Reference
In-Depth Information
Command
In the Personal Information Manager, users might want to update or modify information in their system. This
code demonstrates how the Command pattern can provide update and undo behavior for a location.
In this example, a pair of interfaces model the generic command behavior. The basic command action is defined
by the execute method in Command , while UndoableCommand extends this interface by adding undo and redo
methods.
Example A.40 Command.java
1. public interface Command{
2. public void execute();
3. }
Example A.41 UndoableCommand.java
1. public interface UndoableCommand extends Command{
2. public void undo();
3. public void redo();
4. }
In the PIM, the location of an appointment will be used to implement an undoable command. An appointment
stores a description of an event, the people involved, the location, and the start and end time(s).
Example A.42 Appointment.java
1. import java.util.Date;
2. public class Appointment{
3. private String reason;
4. private Contact[] contacts;
5. private Location location;
6. private Date startDate;
7. private Date endDate;
8.
9. public Appointment(String reason, Contact[] contacts, Location location, Date startDate,
Date endDate){
10. this.reason = reason;
11. this.contacts = contacts;
12. this.location = location;
13. this.startDate = startDate;
14. this.endDate = endDate;
15. }
16.
17. public String getReason(){ return reason; }
18. public Contact[] getContacts(){ return contacts; }
19. public Location getLocation(){ return location; }
20. public Date getStartDate(){ return startDate; }
21. public Date getEndDate(){ return endDate; }
22.
23. public void setLocation(Location location){ this.location = location; }
24.
25. public String toString(){
26. return "Appointment:" + "\n Reason: " + reason +
27. "\n Location: " + location + "\n Start: " +
28. startDate + "\n End: " + endDate + "\n";
29. }
30. }
The class ChangeLocationCommand implements the UndoableCommand interface and provides the behavior
required to change the location for an appointment.
Example A.43 ChangeLocationCommand.java
1. public class ChangeLocationCommand implements UndoableCommand{
2. private Appointment appointment;
3. private Location oldLocation;
4. private Location newLocation;
5. private LocationEditor editor;
6.
7. public Appointment getAppointment(){ return appointment; }
8.
9. public void setAppointment(Appointment appointment){ this.appointment = appointment; }
10. public void setLocationEditor(LocationEditor locationEditor){ editor = locationEditor; }
 
Search WWH ::




Custom Search