Java Reference
In-Depth Information
Example
Application users want the option of undoing previous commands. To support that functionality, a history list is
needed. That history list has to be accessible from everywhere in the PIM and only one instance of it is needed.
Therefore, it's a perfect candidate for the Singleton pattern.
Example 1.20 HistoryList.java
1. import java.util.ArrayList;
2. import java.util.Collections;
3. import java.util.List;
4. public class HistoryList{
5. private List history = Collections.synchronizedList(new ArrayList());
6. private static HistoryList instance = new HistoryList();
7.
8. private HistoryList(){ }
9.
10. public static HistoryList getInstance(){
11. return instance;
12. }
13.
14. public void addCommand(String command){
15. history.add(command);
16. }
17.
18. public Object undoCommand(){
19. return history.remove(history.size() - 1);
20. }
21.
22. public String toString(){
23. StringBuffer result = new StringBuffer();
24. for (int i = 0; i < history.size(); i++){
25. result.append(" ");
26. result.append(history.get(i));
27. result.append("\n");
28. }
29. return result.toString();
30. }
31. }
The HistoryList maintains a static reference to an instance of itself, has a private constructor, and uses a static
method getInstance to provide a single history list object to all parts of the PIM. The additional variable in
HistoryList , history , is a List object used to track the command strings. The HistoryList provides two
methods, addCommand and undoCommand to support adding and removing commands from the list.
Search WWH ::




Custom Search