Java Validation With Dynamic Proxies
By Eric Olson2005-05-14
The business object factory
I can tie all this together with one final piece of code, which will actually create the dynamic proxy classes and attach the correct invocation handler to it. The simplest approach is to encapsulate the creation of the proxy class within the Factory pattern.
Many business object frameworks employee a Factory pattern to create concrete implementations of their business object interfaces, such as the User interface. Creating a new business object instance is, therefore, simply a matter of calling a factory method: All the details behind the creation of the object are left up to the factory, and clients remain ignorant of how the implementation is actually constructed. Listing 6 shows how to create a dynamic proxy class for the User interface (using the UserImpl implementation class), while passing all method invocations through the invocation handler.
Listing 6. The UserFactory
/**Notice that the Proxy.newProxyInstance() method takes three arguments: the classloader in which the dynamic proxy class is defined; the Class array that contains all the interfaces the dynamic proxy class will implement (I've only implemented the User interface in the factory, although I could specify any interfaces that I wanted to implement); and the invocation handler to handle the method invocations. I've also created a new instance of the UserImpl implementation class and passed it to the invocation handler. The invocation handler will use the UserImpl class to delegate all business method invocations.
* Creates a new User instance.
*/
public static User create() {
return(User)Proxy.newProxyInstance(User.class.getClassLoader(),
new Class[] {User.class},
new BusinessObjectInvocationHandler(new UserImpl()));
}
Tutorial Pages:
» Decouple validation processes from your business object implementations
» Tightly coupled validation
» Loosely coupled validation
» The dynamic proxy approach
» The invocation handler
» The business object implementation
» The business object factory
» Drawbacks of dynamic proxies
» Other uses for dynamic proxies
» Conclusion
» Resources
First published by
