By Jeff Chilton
"Success depends upon previous preparation, and without such preparation there is sure to be failure."
-- Confucius (ancient Chinese philosopher, 551BC-479BC)
If you have been following this series, you're now intimately familiar with our little framework for populating HTML select statements with options from a variety of potential sources. If you have not, you might want to go back and take a look at Parts I, II, and III before you go too far, just to get a little background on what we have accomplished so far.
Certainly, the framework as we left it last time could be considered complete as is; however, there is one little flaw that I don't care for as it stands, and I would like to correct that. Our components are, in fact, reusable and externally configurable, and are even interchangeable to a large degree. The problem that I have with things the way they stand is that the using applications are the ones that have to do the configuring. I like to build reusable applications that are pretty ignorant of their implementation-specific differences, which means that I don't like to see the application module passing configuration parameters to the components they're using. My preference is for the application modules to receive their components pre-configured through some process that delivers the components already set up and ready to go. I've found that the simplest way to do that is to create a component factory.
Component factory concepts
A component factory is just what the name implies: something that produces components. The basic component for our little framework is the OptionListSource. Physically, the OptionListSource is a Java Interface, but you can refer to Java objects by the name of any Interface that the object implements, and this is the most generic way to reference a collection of similar-but-different components that all serve the same purpose.
Generally speaking, the application modules will assume the role of consumer in the factory/consumer relationship. The consumer orders its components from the factory, and the factory fills orders by instantiating and configuring objects based on the configuration parameters in effect for the application. The factory deals with the configuration issues, selects the specific implementation to instantiate, and passes all of the appropriate parameters to the component before returning it to the consumer. From the perspective of the consumer, there is no specific knowledge of whether their OptionListSource object is a SimpleObjectListSource, a PropertiesOptionListSource, an SqlOptionListSource, or some other yet-to-be-conceived implementation. Not only does the consumer not know, it doesn't need to know, and really shouldn't care, since all implementers of the OptionListSource interface support the exact same behavior.