Developing Web Applications With Ant by Richard Hightower - HTML preview

PLEASE NOTE: This is an HTML preview only and some elements such as links or page numbers may be incorrect.
Download the book in PDF, ePub, Kindle for a complete version.

Overview of Model Classes

You use the GreetingFactory class to create a Greeting object. Here is the code for GreetingFactory: package xptoolkit.model;
public class GreetingFactory {
private GreetingFactory(){}
public Greeting getGreeting()throws Exception {
String clazz = System.getProperty("Greeting.class",
"xptoolkit.model.GreetingBean");
return (Greeting)Class.forName(clazz).newInstance();
}

public static GreetingFactory getGreetingFactory(){
return new GreetingFactory();
}

}

 

Next we have a Greeting interface that defines the contract of a Greeting object--that is, what type of behavior it supports. The Greeting interface looks like this:

 

package xptoolkit.model;

public interface Greeting extends java.io.Serializable{ public String getGreeting();
}

Finally, the GreetingBean class implements the Greeting interface. GreetingBean is defined as follows: package xptoolkit.model;
public class GreetingBean implements Greeting{
public GreetingBean(){}

public String getGreeting(){
return "Hello World!";
}
}

GreetingBean returns the message "Hello World!" . To create a Greeting instance, you use GreetingFactory. The default implementation of GreetingFactory gets the implementation class from a property and instantiates an instance of that class with the Class.forName().newInstance() method. It casts the created instance to the Greeting interface.

These two lines of code create the Greeting instance from GreetingFactory's getGreeting() method: String clazz = System.getProperty("Greeting.class",
"xptoolkit.model.GreetingBean"); return (Greeting)Class.forName(clazz).newInstance();

Thus, any class that implements the Greeting interface can substitute for the Greeting.class system property. Then, when the class is instantiated with the factory's getGreeting() method, the application uses the new implementation of the Greeting interface.

In the book Java Tools for Extreme Programming (also published by Wiley), we use this technique to transparently add support for EJBs to the Web application. In that book we also create an Ant script that can deploy the same Web application to use either enterprise beans or another bean implementation just by setting an Ant property (and some Ant filter magic). We also map the Greeting interface with the use bean action of a JSP when we implement the Model 2 using servlets and JSP.