stockList.add(”Stocks”); stockList.add(”Bonds”); stockList.add(”Mutual Funds”); stockList.addItemListener(this); //Plot button along bottom of display Panel p1 = new Panel(); p1.setBackground(Color.lightGray); add(”South”, p1); Plot = new Button(”Plot”); Plot.setEnabled(false); //disabled until stock picked Plot.addActionListener(this); p1.add(Plot); //right is empty at first choicePanel = new Panel(); choicePanel.setBackground(Color.lightGray); p.add(choicePanel); w = new Winder(); //intercepts WindowClosing addWindowListener(w); setBounds(100, 100, 300, 200); setVisible(true); } In this simple pro gram, we keep our three lists of investments in three Vectors called Stocks, Bonds and Mutuals. We load them with arbitrary values as part of program initialization: Mutuals = new Vector(); Mutuals.addElement(”Fidelity Magellan”); Mutuals.addElement(”T Rowe Price”); Mutuals.addElement(”Vanguard PrimeCap”); Mutuals.addElement(”Lindner Fund”); and so forth. In a real system, we d probably read them in from a file or database. Then, when the user clicks on one of the three investment types in the left list box, we pass the equivalent vector to our Factory, which returns one of the builders: private void stockList_Click() { Vector v = null; int index = stockList.getSelectedIndex(); choicePanel.removeAll(); //remove previous ui panel //this just switches among 3 different Vectors //and passes the one you select to the Builder pattern switch(index) {
Note: If you are looking for good and high quality web space to host and run your application check Lunarwebhost Java Web Hosting services
multiChoice ui; //This class returns a Panel containing //a set of choices displayed by one of //several UI methods. public multiChoice getChoiceUI(Vector choices) { if(choices.size() <=3) //return a panel of checkboxes ui = new checkBoxChoice(choices); else //return a multi-select list box panel ui = new listboxChoice(choices); return ui; } } In the language of Design Patterns, this factory class is called the Director, and the actual classes derived from multiChoice are each Builders. Calling the Builders Since we re going to need one or more builders, we might have called our main class Architect or Contractor, but since we re dealing with lists of investments, we ll just call it WealthBuilder. In this main class, we create the user interface, consisting of a BorderLayout with the center divided into a 1 x 2 GridLayout. The left part contains our list of investment types and the right an empty panel that we ll fill depending on which kind of investments are selected. public { } wealthBuilder() super("Wealth Builder"); setGUI(); buildStockLists(); choiceFactory cfact; //frame title bar//set up display//create stock lists//the factory //---------------------------------private void setGUI() { setLayout(new BorderLayout()); Panel p = new Panel(); add("Center", p); //center contains left and right panels p.setLayout(new GridLayout(1,2)); //left is list of stocks stockList= new List(10); stockList.addItemListener(this); p.add(stockList);
Note: If you are looking for good and high quality web space to host and run your application check Lunarwebhost Java Web Hosting services
Now, let s consider how we can build the interface to carry out this variable display. We ll start with a multiChoice abstract class that defines the methods we need to implement: abstract class multiChoice { //This is the abstract base class //that the listbox and checkbox choice panels //are derived from Vector choices; //array of labels //——————————————-public multiChoice(Vector choiceList) { choices = choiceList; //save list } //to be implemented in derived classes abstract public Panel getUI(); //return a Panel of components abstract public String[] getSelected(); //get list of items abstract public void clearAll(); //clear selections } The getUI method returns a Panel container with a multiple-choice display. The two displays we re using here — a checkbox panel or a list box panel — are derived from this abstract class: class listboxChoice extends multiChoice or class checkBoxChoice extends multiChoice Then we create a simple Factory class that decides which of these two classes to return: class choiceFactory {
Note: If you are looking for good and high quality web space to host and run your application check Lunarwebhost JSP Web Hosting services
An Investment Tracker Let s consider a somewhat simpler case where it would be useful to have a class build our UI for us. Suppose we are going to write a program to keep track of the performance of our investments. We might have stocks, bonds and mutual funds, and we d like to display a list of our holdings in each category so we can select one or more of the investments and plot their comparative performance. Even though we can t predict in advance how many of each kind of investment we might own at any given time, we d like to have a display that is easy to use for either a large number of funds (such as stocks) or a small number of funds (such as mutual funds). In each case, we want some sort of a multiple-choice display so that we can select one or more funds to plot. If there is a large number of funds, we ll use a multi-choice list box and if there are 3 or fewer funds, we ll use a set of check boxes. We want our Builder class to generate an interface that depends on the number of items to be displayed, and yet have the same methods for returning the results. Our displays are shown below. The first display contains a large number of stocks and the second a small number of bonds.
Note: If you are looking for good and high quality web space to host and run your application check Lunarwebhost Tomcat Web Hosting services
THE BUILDER PATTERN We have already seen that the Factory Pattern returns one of several different subclasses depending on the data passed to in arguments to the creation methods. But suppose we don t want just a computing algorithm, but a whole different user interface depending on the data we need to display. A typical example might be your E-mail address book. You probably have both people and groups of people in your address book, and you would expect the display for the address book to change so that the People screen has places for first and last name, company, E-mail address and phone number. On the other hand if you were displaying a group address page, you d like to see the name of the group, its purpose, and a list of members and their E-mail addresses. You click on a person and get one display and on a group and get the other display. Let s assume that all E-mail addresses are kept in an object called an Address and that people and groups are derived from this base class as shown below: Address Person Group Depending on which type of Address object we click on, we d like to see a somewhat different display of that object s properties. This is a little more than just a Factory pattern, because we aren t returning objects which are simple descendents of a base display object, but totally different user interfaces made up of different combinations of display objects. The Builder Pattern assembles a number of objects, such as display widgets, in various ways depending on the data. Furthermore, since Java is one of the few languages where you can cleanly separate the data from the display methods into simple objects, Java is the ideal language to implement Builder patterns.
Note: If you are looking for good and high quality web space to host and run your application check Lunarwebhost Tomcat Web Hosting services
2. You can easily change a Singleton to allow a small number of instances where this is allowable and meaningful.
Note: If you are looking for good and high quality web space to host and run your application check Lunarwebhost Java Web Hosting services
if(pr1 != null) System.out.println(”got 1 spooler”); //try to open another spooler –should fail System.out.println(”Opening two spoolers”); pr2 = iSpooler.Instance(); if(pr2 == null) System.out.println(”no instance available”); And, should you try to create instances of the iSpooler class directly, this will fail at compile time because the constructor has been declared as private. //fails at compile time because constructor is privatized iSpooler pr3 = new iSpooler(); Finding the Singletons in a Large Program In a large, complex program it may not be simple to discover where in the code a Singleton has been instantiated. Remember that in Java, global variables do not really exist, so you can t save these Singletons conveniently in a single place. One solution is to create such singletons at the beginning of the program and pass them as arguments to the major classes that might need to use them. pr1 = iSpooler.Instance(); Customers cust = new Customers(pr1); A more elaborate solution could be to create a registry of all the Singleton classes in the program and make the registry generally available. Each time a Singleton instantiates itself, it notes that in the Registry. Then any part of the program can ask for the instance of any singleton using an identifying string and get back that instance variable. The disadvantage of the registry approach is that type checking may be reduced, since the table of singletons in the registry probably keeps all of the singletons as Objects, for example in a Hashtable object. And, of course, the registry itself is probably a Singleton and must be passed to all parts of the program using the constructor or various set functions. Other Consequences of the Singleton Pattern 1. It can be difficult to subclass a Singleton, since this can only work if the base Singleton class has not yet been instantiated.
Note: If you are looking for good and high quality web space to host and run your application check Lunarwebhost Java Web Hosting services
One advantage of the final class approach is that you don t have to wrap things in awkward try blocks. The disadvantage is that if you would like to drop the restrictions of Singleton status, this is easier to do in the exception style class structure. We d have a lot of reprogramming to do to make the static approach allow multiple instances. Creating Singleton Using a Static Method Another approach, suggested by Design Patterns, is to create Singletons using a static method to issue and keep track of instances. To prevent instantiating the class more than once, we make the constructor private so an instance can only be created from within the static method of the class. class iSpooler { //this is a prototype for a printer-spooler class //such that only one instance can ever exist static boolean instance_flag = false; //true if 1 instance //the constructor is privatized// but need not have any content private iSpooler() { } //static Instance method returns one instance or null static public iSpooler Instance() { if (! instance_flag) { instance_flag = true; return new iSpooler(); //only callable from within } else return null; //return no further instances } //——————————————public void finalize() { instance_flag = false; } } One major advantage to this approach is that you don t have to worry about exception handling if the singleton already exists– you simply get a null return from the Instance method: iSpooler pr1, pr2; //open one spooler–this should always work System.out.println(”Opening one spooler”); pr1 = iSpooler.Instance();
Note: If you are looking for good and high quality web space to host and run your application check Lunarwebhost Java Web Hosting services
try{ pr2 = new PrintSpooler(); } catch (SingletonException e) {System.out.println(e.getMessage());} } } Then, if we execute this program, we get the following results: Opening one spooler printer opened Opening two spoolers Only one spooler allowed where the last line indicates than an exception was thrown as expected. You will find the complete source of this program on the example CD-ROM as singleSpooler.java. Static Classes as Singleton Patterns There already is a kind of Singleton class in the standard Java class libraries: the Math class. This is a class that is declared final and all methods are declared static, meaning that the class cannot be extended. The purpose of the Math class is to wrap a number of common mathematical functions such as sin and log in a class-like structure, since the Java language does not support functions that are not methods in a class. You can use the same approach to a Singleton pattern, making it a final class. You can t create any instance of classes like Math, and can only call the static methods directly in the existing final class. final class PrintSpooler { //a static class implementation of Singleton pattern static public void print(String s) { System.out.println(s); } } //============================== public class staticPrint { public static void main(String argv[]) { Printer.print(”here it is”); } }
Note: If you are looking for good and high quality web space to host and run your application check Lunarwebhost JSP Web Hosting services
Throwing the Exception Let s write the skeleton of our PrintSpooler class; we ll omit all of the printing methods and just concentrate on correctly implementing the Singleton pattern: class PrintSpooler { //this is a prototype for a printer-spooler class //such that only one instance can ever exist static boolean instance_flag=false; //true if 1 instance public PrintSpooler() throws SingletonException { if (instance_flag) throw new SingletonException(”Only one spooler allowed”); else instance_flag = true; //set flag for 1 instance System.out.println(”spooler opened”); } //——————————————public void finalize() { instance_flag = false; //clear if destroyed } } Creating an Instance of the Class Now that we ve created our simple Singleton pattern in the PrintSpooler class, let s see how we use it. Remember that we must enclose every method that may throw an exception in a try - catch block. public class singleSpooler { static public void main(String argv[]) { PrintSpooler pr1, pr2; //open one spooler–this should always work System.out.println(”Opening one spooler”); try{ pr1 = new PrintSpooler(); } catch (SingletonException e) {System.out.println(e.getMessage());} //try to open another spooler –should fail System.out.println(”Opening two spoolers”);
Note: If you are looking for good and high quality web space to host and run your application check Lunarwebhost JSP Web Hosting services