Class 2 |
Intermediate Java 30-IT-397 |
|
Challenge Solution
-
Make an abstract superclass, InsuranceFileInput, that implements the Command
interface.
-
Give it an abstract method called read().
-
Annuity, Life, Car, Homeowner, and Business extend InsuranceFileInput.
Thus, they implement the read() method and provide the logic to read the
data specific to that file type.
-
Again, using the command pattern, our class InsuranceFileReader can call
the read() method to read (and possibly store) the contents of the files.
-
But how do we know which file to read?
-
InsuranceFileReader implements the factory method.
-
The files need to be named in a manner that identifies the file type.
-
ANNUITY0001.XML, ANNUITY0002.XML, ANNUITY0003.XML, etc., are files that
can be processed with the Annuity class.
-
BUSINESS0001.XML, BUSINESS0002.XML, BUSINESS0003.XML are files that can
be processed with the Business class.
-
Then, InsuranceFileReader can iterate through the files in the directory,
one at a time. It reads in the name of the file, and passes this
name to the factory method, which will create an instance of the appropriate
class to read the file.
-
Once the object representing the file has been instantiated (an object
of type Annuity, an object of type Business, etc.), it is passed to the
method implementing the command pattern that will call the run()
method on that object.
-
And magic, a forward thinking, pattern implementing, non-if-test-using
program.
-
Does it work?
-
Yes. I used this exact same technique at a former employer to read
in file types, just like this.
-
Sure enough, a new file type was implemented. I wrote a class that
extended the counterpart of the InsuranceFileInput class above, and dropped
it into a directory that contained only the other subclasses. The
first time a file of this new type arrived, the counterpart to the InsuranceFileReader
read the file, without requiring any changes.
Created by: Brandan Jones
December 17, 2001