During development of your Struts-based web tier, you want to be able to test your page flow, action forms and validation independent of your persistency layer, which may be implemented with any Object Relational framework.
That is were the abstract factory design pattern comes in handy. Suppose we want to test our Struts-based code using mock objects (the Struts testcase framework allows for both an in-container based approach as well as a mock objects-based one). In the test environment we want to obtain the data from our mock objects, whereas in real life, we want to get our data from our, let’s say EJBs.
This is solved by introducing the abstract factory design pattern. We define an abstract factory that returns a
DataSource. We subclass two concrete factories, a
BeanDataSourceFactory and a
MockObjectDataSourceFactory, which return a
BeanDataSource and a
MockObjectDataSource respectively. Of course, both the bean and mock object based data sources implement
DataSource, so we can always upcast to this interface, and can remain ignorant in the remainder of the code of the particular data source we are using.
As an additional bonus, we can now swap one persistency layer with another, without having to change anything in our web tier. This is probably what they mean when they mention that unit tests improve your overall design 😉
How this concrete case matches the general abstract factory UML class diagram outlined here, is left as an exercise to the reader.
- Struts testcase JUnit-based test framework
- Abstract factory in the Core J2EE patterns blueprints
- See (the last paragraph in particular of) this explanation of the abstract factory design pattern for a gentle introduction what this pattern is all about
- The freely downloadable book Jakarta Struts live, in which chapter two is completely devoted to Test Driven Development (TDD) with Struts.