Java Reference
In-Depth Information
Singleton
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 implementation of the Singleton pattern.
Example A.29
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.
The
SingletonGui
class provides a basic Swing GUI that demonstrates how the
HistoryList
might be used in a
PIM editor. This GUI provides a basic set of commands: create contact, create appointment, undo, refresh and
exit. For the create commands, you retrieve the
HistoryList
with a call to its static getInstance method, then call
the
addCommand
method. For the undo command, you call
getInstance
followed by the
undoCommand
method.
The
refresh
method calls the
toString
method in the
HistoryList
to retrieve the current set of history list
entries for display.
Example A.30
SingletonGUI.java
1. import java.awt.Container;
2. import javax.swing.BoxLayout;
3. import javax.swing.JButton;
4. import javax.swing.JFrame;
5. import javax.swing.JPanel;
6. import javax.swing.JTextArea;
7. import java.awt.event.ActionEvent;
8. import java.awt.event.ActionListener;
9. import java.awt.event.WindowAdapter;
10. import java.awt.event.WindowEvent;
11. public class SingletonGui implements ActionListener{
12. private JFrame mainFrame;
13. private JTextArea display;
14. private JButton newContact, newAppointment, undo, refresh, exit;
15. private JPanel controlPanel, displayPanel;
16. private static int historyCount;
17.
18. public void createGui(){
19. mainFrame = new JFrame("Singleton Pattern Example");