Introducing the Factory
Now we're down to the really fun part. We've got our interface (Ferret) defined, and we've got at least two classes (GoogleFinder and GoogleSpecificFinder) that implement it. We've got an application that can use one or the other to instantiate a Ferret object and use it to perform an analysis.
Now it's time for the factory.
The idea behind a factory is that rather than create a specific class, we can create a factory and then let the factory decide what class to instantiate.
In some ways, Java factories are much like real-world factories; we might have a factory that produces television sets. Each television set has specific features about it (such as a screen and a way to change the channel), but a particularly flexible factory might turn out hand-held models with a radio-like dial and projection setswith a three-pound remote control that also makes coffee. It all depends on what management wants at any given time.
In our case, we will create a factory that produces Ferrets. In Listing 6, we'll start simple, with a factory (FerretFactory) that always produces a GoogleFinder-variety Ferret.
Listing 6 Simple Factory
package org.chase.research; public class FerretFactory { public Ferret newFerret() { return new org.chase.ferrets.GoogleFinder(); } }
This class has only one method, and all it does is return an instance of GoogleFinder as a Ferret object. To use the factory, we need to make a change to our ResearchProject application, as shown in Listing 7.
Listing 7 Using the Factory
import org.chase.research.Ferret; import org.chase.research.FerretFactory; public class ResearchProject { public static void main(String[] args) { if (args.length > 0) { String searchTerm = args[0]; FerretFactory ferretFactory = new FerretFactory(); Ferret theFerret = ferretFactory.newFerret(); System.out.println("Getting Results ..."); theFerret.find(searchTerm); ...
Notice, first of all, that we removed the import statement for GoogleFinder and GoogleSpecificFinder, and that neither is mentioned anywhere in the application. Instead, we're instantiating the FerretFactory and then using the newFerret() method to return a Ferret object.
The overall application has no idea what class is implementing the Ferret, and that's as it should be. If we run the ResearchProject application, however, we can see pretty quickly from the results that it's GoogleFinder, as noted within the FerretFactory.