Java Reference
In-Depth Information
7. private TaskChangeObservable notifier;
8. public TaskSelectorPanel(TaskChangeObservable newNotifier){
9. notifier = newNotifier;
10. createGui();
11. }
12. public void createGui(){
13. selector = new JComboBox();
14. selector.addActionListener(this);
15. add(selector);
16. }
17. public void actionPerformed(ActionEvent evt){
18. notifier.selectTask((Task)selector.getSelectedItem());
19. }
20. public void setTaskChangeObservable(TaskChangeObservable newNotifier){
21. notifier = newNotifier;
22. }
23.
24. public void taskAdded(Task task){
25. selector.addItem(task);
26. }
27. public void taskChanged(Task task){ }
28. public void taskSelected(Task task){ }
29. }
A feature of the Observer pattern is that the Observable uses a standard interface for its Observers —in this
case, TaskChangeObserver . This means that the Observer pattern is more generic than the Mediator pattern, but
also that the observers may receive some unwanted message traffic. For instance, the TaskEditorPanel takes no
action when its taskAdded and taskChanged methods are called.
The Task class represents the business object in the GUI, which in this demonstration is a simple job.
Example A.95 Task.java
1. public class Task{
2. private String name = "";
3. private String notes = "";
4. private double timeRequired;
5.
6. public Task(){ }
7. public Task(String newName, String newNotes, double newTimeRequired){
8. name = newName;
9. notes = newNotes;
10. timeRequired = newTimeRequired;
11. }
12.
13. public String getName(){ return name; }
14. public String getNotes(){ return notes; }
15. public double getTimeRequired(){ return timeRequired; }
16. public void setName(String newName){ name = newName; }
17. public void setTimeRequired(double newTimeRequired){ timeRequired = newTimeRequired; }
18. public void setNotes(String newNotes){ notes = newNotes; }
19. public String toString(){ return name + " " + notes; }
20. }
RunPattern creates the GUI for this example, creating the observable and its observers in the process.
Example A.96 RunPattern.java
1. public class RunPattern{
2. public static void main(String [] arguments){
3. System.out.println("Example for the Observer pattern");
4. System.out.println("This demonstration uses a central observable");
5. System.out.println(" object to send change notifications to several");
6. System.out.println(" JPanels in a GUI. Each JPanel is an Observer,");
7. System.out.println(" receiving notifcations when there has been some");
8. System.out.println(" change in the shared Task that is being edited.");
9. System.out.println();
10.
11. System.out.println("Creating the ObserverGui");
12. ObserverGui application = new ObserverGui();
13. application.createGui();
14. }
15. }
 
Search WWH ::




Custom Search