The Factory Pattern


The Singleton Pattern

The Singleton is used when your application needs only one instance, or a controlled number of instances, of a particular type. Examples of Singletons include application session objects and application properties objects. The Singleton is often used to implement other patterns such as the Factory. (The Factory pattern is discussed below.)

The general approach to implementing a Singleton is to create a class that has a protected or private constructor and a public static method named getInstance(). Example 25.1 shows the code for a class named CommandProperties that implements the Singleton design pattern.

Example 25.1: CommandProperties.java

image from book
 1     package com.pulpfreepress.utils; 2 3     import java.util.*; 4     import java.io.*; 5 6     public class CommandProperties extends Properties { 7 8        // class constants - default key strings 9        public static final String PROPERTIES_FILE             = "PROPERTIES_FILE"; 10       public static final String NEWHOURLYEMPLOYEE_COMMAND   = "NewHourlyEmployee"; 11       public static final String NEWSALARIEDEMPLOYEE_COMMAND = "NewSalariedEmployee"; 12       public static final String EXIT_COMMAND                = "Exit"; 13       public static final String LIST_COMMAND                = "List"; 14       public static final String SORT_COMMAND                = "Sort"; 15       public static final String SAVE_COMMAND                = "Save"; 16       public static final String EDITEMPLOYEE_COMMAND        = "EditEmployee"; 17       public static final String DELETEEMPLOYEE_COMMAND      = "DeleteEmployee"; 18       public static final String LOAD_COMMAND = "Load"; 19 20       // class constants - default value strings 21       private static final String PROPERTIES_FILE_VALUE= "Command.properties"; 22       private static final String NEWHOURLYEMPLOYEE_COMMAND_CLASSNAME 23                             = "com.pulpfreepress.commands.NewHourlyEmployeeCommand"; 24       private static final String NEWSALARIEDEMPLOYEE_COMMAND_CLASSNAME 25                             = "com.pulpfreepress.commands.NewSalariedEmployeeCommand"; 26       private static final String EXIT_COMMAND_CLASSNAME 27                             = "com.pulpfreepress.commands.ApplicationExitCommand"; 28       private static final String LIST_COMMAND_CLASSNAME 29                             = "com.pulpfreepress.commands.ListEmployeesCommand"; 30       private static final String SORT_COMMAND_CLASSNAME 31                             = "com.pulpfreepress.commands.SortEmployeesCommand"; 32       private static final String SAVE_COMMAND_CLASSNAME 33                             = "com.pulpfreepress.commands.SaveEmployeesCommand"; 34       private static final String EDITEMPLOYEE_COMMAND_CLASSNAME 35                             = "com.pulpfreepress.commands.EditEmployeeCommand"; 36       private static final String DELETEEMPLOYEE_COMMAND_CLASSNAME 37                             = "com.pulpfreepress.commands.DeleteEmployeeCommand"; 38       private static final String LOAD_COMMAND_CLASSNAME 39                             = "com.pulpfreepress.commands.LoadEmployeesCommand"; 40 41       // class variables 42       private static CommandProperties _properties_object = null; 43 44       private CommandProperties( String properties_file ){ 45          try{ 46             FileInputStream fis = new FileInputStream(properties_file); 47             load(fis); 48           } catch(Exception e) { 49              System.out.println("Problem opening properties file!"); 50              System.out.println("Bootstrapping properties..."); 51              try{ 52                FileOutputStream fos = new FileOutputStream(PROPERTIES_FILE_VALUE); 53                setProperty(PROPERTIES_FILE, PROPERTIES_FILE_VALUE); 54                setProperty(NEWHOURLYEMPLOYEE_COMMAND, NEWHOURLYEMPLOYEE_COMMAND_CLASSNAME); 55                setProperty(NEWSALARIEDEMPLOYEE_COMMAND, NEWSALARIEDEMPLOYEE_COMMAND_CLASSNAME); 56                setProperty(EXIT_COMMAND, EXIT_COMMAND_CLASSNAME); 57                setProperty(LIST_COMMAND, LIST_COMMAND_CLASSNAME); 58                setProperty(SORT_COMMAND, SORT_COMMAND_CLASSNAME); 59                setProperty(SAVE_COMMAND, SAVE_COMMAND_CLASSNAME); 60                setProperty(EDITEMPLOYEE_COMMAND, EDITEMPLOYEE_COMMAND_CLASSNAME); 61                setProperty(DELETEEMPLOYEE_COMMAND, DELETEEMPLOYEE_COMMAND_CLASSNAME); 62                setProperty(LOAD_COMMAND, LOAD_COMMAND_CLASSNAME); 63 64                super.store(fos, "CommandProperties File - Edit Carefully"); 65                fos.close(); 66              }catch(Exception e2){ System.out.println("Uh ohh...Bigger problems exist!"); } 67            } 68        } 69 70    /************************************************************************************************** 71    *  Private default constructor. Applications will get an instance via the getInstance() method. 72    *  @see getInstance() 73    ***************************************************************************************************/ 74       private CommandProperties(){ 75           this(PROPERTIES_FILE_VALUE); 76       } 77 78    /************************************************************************************************** 79    *  The store() method attempts to persist its properties collection. 80    ***************************************************************************************************/ 81       public void store(){ 82         try{ 83           FileOutputStream fos = new 84                 FileOutputStream(getProperty(PROPERTIES_FILE)); 85           super.store(fos, "CommandProperties File"); 86           fos.close(); 87         }catch(Exception e){ System.out.println("Trouble storing properties!"); } 88       } 89 90    /************************************************************************************************** 91    *  getInstance() returns a singleton instance if the CommandProperties object. 92    ***************************************************************************************************/ 93       public static CommandProperties getInstance(){ 94         if(_properties_object == null){ 95            _properties_object = new CommandProperties(); 96           97         return _properties_object; 98      } 99    } // end CommandProperties class definition
image from book

Referring to example 25.1 — the CommandProperties class is used to create a menu command-to-command handler class mapping file named image from book command.properties. The CommandProperties class is used in the comprehensive example presented at the end of the chapter. Notice the declaration on line 42 of a private static field of type CommandProperties named _properties_object. Notice also that both constructors are declared private. The static getInstance() method begins on line 93. It ensures the existence of only one instance of CommandProperties.

Quick Review

The Singleton pattern is used when only one instance of a particular class type is required to exist in your program. The general approach to creating a Singleton is to make the constructor protected or private and provide a public static method named getInstance() that returns the same instance of the class in question.




Java For Artists(c) The Art, Philosophy, and Science of Object-Oriented Programming
Java For Artists: The Art, Philosophy, And Science Of Object-Oriented Programming
ISBN: 1932504052
EAN: 2147483647
Year: 2007
Pages: 452

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net