VisionSet said:
I have a class that is instantiable via a few factory methods.
Each method produces a slightly different object that uses or doesn't
various attributes.
To make the public interface better I want the factory methods to return
different interface types.
I thought I'd have different inner interfaces that describe the contracts of
the objects returned by the factory methods.
But my class must implement these and I get 'cyclic inheritance
involving...' errors.
How do you typically implement this pattern, has it got a name?
Evidently, either the interfaces must not be nested in the class in
question or the objects you return must be of a subclass of your class.
In the latter case, the subclass can be trivial; for instance, this
compiles fine for me:
public class C {
public static interface I {
void foo();
}
public void foo() {}
public static I getInstance() {
class CI extends C implements I {}
return new CI();
}
}
I wouldn't say that that's something I typically do, though.
As for as the name of the pattern? As I understand it, you want to have
a class that clients use to obtain objects suitable (and perhaps
suitably configured) for various specific uses. That would be the
Factory pattern; probably a static factory in this case for the fewest
changes from what you already have. Once you hide the fact that the
objects returned by your factory are instances of the factory class (by
assigning them to the appropriate interface type) then that detail is no
longer relevant. Clients of the class cannot assume it to be the case
unless you document it, and if you're going to document it then why are
you bothering with the exercise in the first place?
I'm guessing that that wasn't what you were hoping to hear regarding the
pattern name, but I'm not sure how else to answer the question. Perhaps
it's because I don't understand why you want to do quite what you first
described (that gives the compiler error). If you want to hand out
objects of different declared types then why is it important that they
all be instances of the same class? Or to turn it the other way around,
if it is important that the objects you want to hand out all be
instances of the same class then what do you gain by declaring them with
some narrower type?
John Bollinger
(e-mail address removed)