Understanding Java Factories
Java factories are a handy way to allow other programmers to create "plug in" components for an API. Increasingly common in open-source applications, factories enable designers to allow other programmers to add their own code without jeopardizing the overall architecture.
In this article, we'll look at how factories work and how you can use them in your own applicationsand in other people's. We'll do this by creating an application that performs searches using Google's new Web services API. You'll create two different "ferrets" and then see how using a factory allows you to choose which one is actually loaded at any given time. You'll even be able to specify a completely different ferret at run time.
Overall Application
The application itself simply allows a user to enter a research term on the command line. The application then goes out and checks a search engine for the number of results for that term, provides the first result, and then provides the complete available set.
NOTE
The Google API provides a maximum of 10 results at a time.
The part of the application that actually goes out and does the research is called the ferret, and this is the object that can be changed out for another implementation. In this article, we'll take a brief look at two different ferrets, each of which performs a search. Ultimately, the application lets you build your own ferret, allowing you to search any source you want and then plug it in to the application. The only requirement is that the ferret must implement the proper interface.
This last bit is crucial. The whole idea is to get people to use standard objects and methods. Otherwise, what's the point of having a common API? Using a factory enables you to give them the freedom to come up with their own implementations without hard-coding their own classes and methods into the application.