Re: Constructor
Eric l wrote:
- Make all the constructors private and use factory methods,
with the drawback that the class can't be extended. (This
approach avoids the quibble mentioned above, assuming the
registration occurs in the factory rather than in the
constructor.)
This is what I would do. Bloch even talks about factory methods in Item
1 of Effective Java. I think there aren't enough folks using factory
methods if he puts it as #1. They can be clumsy to work with, and seem
un-OO, but factory methods are a great pattern and should be used more
(when appropriate, of course).
I wonder if providing an abstract class to base future classes on would
work, if extension is important. Hmm, but it would be possible to use
the class outside of the factory method. Documentation might work
here... so might relentlessly testing each object passed in to make sure
it was registered. A clever design might even eliminate most of the
overhead by only checking on a few critical methods.
I guess you could call your base class the "implementation" class, then
use a restricted wrapper to get the real object to work on.
public abstract class Implementation {}
final public class Wrapper {
Wrapper( Implementation i ) {} // package private
}
public class Factory {
private Factory() {}
public static Wrapper getNew( Implementation i ) {
Wrapper w = new Wrapper( i );
Registry.register( w ); // not shown
return w;
}
}
So if all your methods require a Wrapper, the compiler does the checking
for you. This also seems Dependency Injection-y, which might be a good
thing.