Re: passing a Factory to a method to create a generic instance
Tom Anderson wrote:
public static List<AsignmentLoadable> loadAll(File file) {
List<AsignmentLoadable> al =
new ArrayList<AsignmentLoadable>();
//List<String> lines = getLines(file);
IOStream ios = new FileIOStream( file );
while( (AssignmentLoadable a = getNextObject( ios )) != null )
a.assignmentLoad( ios );
al.add( a );
}
return al;
}
On a style note, my beef with this design is that you have the potential
to have instantiated but uninitialised objects floating about, which
makes me nervous. I'd rather do it all properly in the constructor
myself, so that we have a guarantee that in all cases, instances are
properly initialised.
a.assignmentLoad() is supposed to initialize the object, completely,
from the data read from ios. The only way that an object would be
improperly initialized would be if the data was bad or there was an IO
error in the middle of the stream. Or that's what I'm thinking.
Also, i don't get what getNextObject(ios) is doing, or how it knows what
class to instantiate.
It's basically the same as my code below this (which I snipped). Read a
token from the stream, associate that token with a class, instantiate
the class with newInstance().
>> For the factory pattern, it might be better to use package private
>> constructors, then make the factory object part of the package, so it
>> has access to the constructors.
>
> I like this idea!
Thanks. I got this idea primarily from working with JUnit. JUnit makes
unit test objects that are part of the same package as the classes they
test. So you have access to package private methods, although those
methods are not available to other classes outside the package. It's a
handy little back-door into a class.
I think of packages now as Java's way of implementing behavior like C++
"friend" classes.