The Singleton Pattern
An Introduction with Examples in Java |
Prof. David Bernstein |
Computer Science Department |
bernstdh@jmu.edu |
FileViewer
/** * A Frame that is used to view the contents of a file * * This class uses the Singleton pattern * to ensure that there is only one * instance at any point in time. * * @author Prof. David Bernstein, James Madison University * @version 1.0 * */ public class FileViewer { private static boolean exists = false; private static FileViewer instance; /** * Construct a new FileViewer * * Note: This method is private and used only internally */ private FileViewer() { exists = true; } }
FileViewer
/** * Construct a new FileViewer (if one doesn't exist) * or return the existing instance */ public static FileViewer createInstance() { if (!exists) instance = new FileViewer(); // exists will become true return instance; }
FileViewer
/** * Handle valueChanged events * (required by ListSelectionListener) * * @param lse The ListSelectionEvent to handle */ public void valueChanged(ListSelectionEvent lse) { FileViewer fv; String fn; fn = (String)list.getSelectedValue(); fv = FileViewer.createInstance(); fv.load(fn); }
createInstance()
method might
be called by multiple threads, problems can arisecreateInstance()
synchronizedinstance
when it is declared)private static FileViewer instance = new FileViewer();
/** * Return the singleton instance */ public static FileViewer createInstance() { return instance; }