Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
n COMP209 Object Oriented Programming Utility Classes 2 n Mark Hall n n Department of Computer Science Exercise Solutions n Palindrome n Word & letter count Formatting Numbers n Locales n Factory Design Pattern System Runtime n Singleton Design Pattern 1 Palindrome Solutions • Using StringBuffer: public class Palindrome1 { public static void main (String args []) { StringBuffer s = new StringBuffer (args[0]); StringBuffer t = new StringBuffer (args[0]); if (s.toString().equals(t.reverse().toString())) { System.out.println(s+" is a palindrome"); } else { System.out.println(s+" is not a palindrome"); } } } Department of Computer Science 2 Computing word counts and letter frequencies public void process(BufferedReader r) throws IOException { String delims = " \t\n.,!?;:[]{}()%$^&@#></\"\'-_+=`~1234567890"; int lines = 0; int words = 0; int letters = 0; int [] letterFreq = new int [26]; String line; • Using String: public class Palindrome2 { public static void main (String args []) { String s = args[0]; for (int i=0; i<s.length()/2; i++) { if (!(s.charAt(i) == (s.charAt(s.length()-1-i)))) { System.out.println(s+" is not a palindrome"); return; } } System.out.println(s+" is a palindrome"); } } Department of Computer Science Palindrome Solutions 3 Computing word counts and letter frequencies while ((line = r.readLine()) != null) { line = line.toLowerCase(); lines++; StringTokenizer tok = new StringTokenizer(line, delims); while (tok.hasMoreTokens()) { String next = tok.nextToken(); words++; letters += next.length(); for (int i = 0; i < next.length(); i++) { letterFreq[next.charAt(i) - 'a']++; } } } // continued on next slide Formatting Numbers • Example output from the above program: // continued from previous slide System.out.println("Num letters: " + letters + " Num words: " + words + " Num lines: " + lines); for (int i = 0; i < 26; i++) { System.out.println((char)(i + 'a') + ": " + ((double)letterFreq[i] / letters)); } } Department of Computer Science Department of Computer Science 5 Num letters: 1314 Num words: 262 Num lines: 37 a: 0.0745814307458143 b: 0.01293759512937595 c: 0.0380517503805175 d: 0.0289193302891933 e: 0.0989345509893455 . . . • 16 decimal places is probably overkill :-) • What if we wanted to output percentages to one decimal place? Department of Computer Science 6 1 Formatting Numbers • We can make use of java.text.NumberFormat to format numbers for us NumberFormat pf = NumberFormat.getPercentInstance(); pf.setMaximumFractionDigits(1); for (int i = 0; i < 26; i++) { System.out.println((char)(i + 'a') + ": " + pf.format(((double)letterFreq[i] / letters))); } Num letters: 1314 Num words: 262 Num lines: 37 a: 7.5% b: 1.3% c: 3.8% d: 2.9% e: 9.9% NumberFormat • Abstract base class • Provides a number of static creation methods that return various concrete sub classes – Numbers, percentages, currencies – Locale sensitive • Has methods for setting min/max fraction and integer digits, parsing numbers etc. Department of Computer Science 8 NumberFormat NumberFormat • In the previous example we used the default locale for formatting the percentages • Can also specify a locale • We can find out what locales NumberFormat supports by calling the static getAvailableLocales method NumberFormat pf = NumberFormat.getPercentInstance(Locale.GERMAN); Num letters: 1314 Num words: 262 Num lines: 37 a: 7,5% b: 1,3% c: 3,8% d: 2,9% e: 9,9% . . . Department of Computer Science 9 LocaleTest • Prints out locales supported by NumberFormat Locale [] l = NumberFormat.getAvailableLocales(); for (int i = 0; i < l.length; i++) { System.out.println(l[i]); } . . . en_AU en_CA en_GB en_IE en_IN en_NZ en_ZA . . . Department of Computer Science – Returns an array of java.util.Locale objects • Locale encapsulates information about a region—language and country • Construct with ISO standard two or three character country and language codes • Has some static constants for various countries and languages Department of Computer Science 10 Abstract Factory/Factory Method Design Pattern • NumberFormat takes advantage of a variation of the Abstract Factory (and closely related Factory Method) design pattern • Basic idea is to provide a mechanism for creating instances of related objects without specifying their concrete representations – Completely decouple clients from concrete types—instead objects are manipulated polymorphically through a common interface or parent class Department of Computer Science 12 2 Abstract Factory/Factory Method Design Pattern • NumberFormat has two types of factory methods • NumberFormat’s static creation methods are factory methods – They return concrete implementations characterized only by the NumberFormat interface • The factory method’s job is to select the appropriate concrete implementation • Clients do not need to know what concrete implementation they are using Department of Computer Science Abstract Factory/Factory Method Design Pattern – Default factory methods — getPercentInstance(), getNumberInstance(), etc • return NumberFormat objects for the default locale – Parameterized factory methods — getPercentInstance(Locale l), … • return differently configured NumberFormat objects depending on which locale is supplied 13 Department of Computer Science Abstract Factory/Factory Method Design Pattern • Abstract Factory is often used to implement UI toolkits that support different look-and-feel standards, Eg: – Have an abstract WidgetFactory class that defines factory methods for creating different widgets (buttons, scroll bars etc). Also have abstract classes for each kind of widget – Have concrete subclasses of WidgetFactory that supply concrete widgets for different look-and-feels – Could also have a static factory method in the WidgetFactory class to return various concrete subclasses • Java’s Toolkit (awt) class takes this approach to link widget abstractions to platform dependent UI elements 14 java.lang.System • Provides access to a number of systemwide resources – Streams for standard in, out and error — System.in, System.out, System.err • Static methods to reassign in, out and err – Static method exit(int status) — halt the currently running program – Static method currentTimeMillis — returns the current time in milliseconds since Jan 1, 1970 – Static method gc — force the garbage collector to run – arraycopy — fast static method that is overloaded to handle copying arrays of all types Department of Computer Science 16 java.lang.Runtime Java.lang.System • System.arraycopy – Obtain a Runtime object by calling the static method getRuntime() – Takes a source array, source position, destination array, destination position and length – Throws • Some methods: • IndexOutOfBoundsException if accessing outside of either source or destination array’s bounds • ArrayStoreException if there is a type mismatch between source and distination arrays • NullPointerException if either array is null Department of Computer Science Department of Computer Science • Runtime allows a Java application to interact with environment in which the application is running • Can’t construct a Runtime object 17 – int availableProcessors() — # processors available to the virtual machine – long freeMemory() — amount of free memory available to the virtual machine – long maxMemory() — maximum amount of memory that the vitual machine will attempt to use Department of Computer Science 18 3 java.lang.Runtime • Some more methods: – Process exec(String cmd) • Execute named command in a separate process – Process exec(String cmd, String [] envp) • Execute named command with supplied environment settings in a separate process • The exec processes in Runtime create a native process and return an instance of a concrete subclass of Process – Another example of a factory method • The created subprocess does not have its own console or terminal – Process exec(String cmd, String [] envp, File dir) – As a consequence, we can’t use redirection of in/out in the command to be executed (e.g. can’t do “ls -l > blah.txt”) – Process provides access to input and output stream objects that can be used to read and write to/from the subprocess • Execute named command with supplied environment settings and working directory in a separate process • cmd gets parsed using a StringTokenizer • Each element of envp is an environment variable setting with format name=value Department of Computer Science java.lang.Runtime • Process also provides methods to wait for the subprocess to complete and to kill the subprocess 19 Using Runtime to execute a system command try { Runtime r = Runtime.getRuntime(); // get runtime object Process p = r.exec("ls -l"); //exec ls cmd under linux InputStream is = p.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String next; // Read the output of the system process while ((next = br.readLine()) != null) { System.out.println(next); } } catch (Exception ex) { ex.printStackTrace(); } Department of Computer Science Singleton Design Pattern • Sometimes we only ever need a single instance of a class • Runtime is an example of the Singleton design pattern • The intent of the Singleton pattern is to ensure that a class has only one instance, and to provide a global point of access to it – A java class can make use of a private constructor to prevent clients from instantiating objects of the class • Only one Runtime object is ever needed in order to provide an application access to systemwide resources Department of Computer Science Singleton Design Pattern • Primary benefits of the Singleton design pattern – Controlled access to sole instance—the Singleton class has strict control over how and when clients access the sole instance. Ensures that no other instances can be created – Reduced name space—the Singleton pattern is a better solution than using global variables to store sole instances – Permits a variable number of instances—the pattern makes it easy to change your mind and allow more than one instance of the Singleton class 20 22 Readings • Budd, chapter 17 • Budd, section 15.6 and 15.7 • Javadocs for NumberFormat, Locale, System, Runtime and Process • Same approach can be used to control the number of instances that the application uses; only the operation that grants access needs to change Department of Computer Science Department of Computer Science 23 Department of Computer Science 24 4