I have the following problem:
There is a common Factory interface
interface Factory<T> { T create(); }
Now I have two classes T1 and T2, where T2 is a refinement of T1
class T1 { } class T2 extends T1 { }
and two factories for these types:
interface T1Factory extends Factory<T1> { public T1 create(); } interface T2Factory extends Factory<T2> { public T2 create(); }
For these factories, the default implementation will be provided through Generics:
class DefaultFactory<T, F extends Factory<T>> implements Factory<T> { private F factory; ... public T create() { return factory.create(); } }
which should be used to implement factories for T1 and T2.
class DefaultT1Factory extends DefaultFactory<T1,T1Factory> { } class DefaultT2Factory extends DefaultFactory<T2,T2Factory> { }
Before that, it works great. Now the problem. Since T2 is a refinement of T1, Factory for T2 should be used just like Factory for T1.
This requires that T2Factory be obtained from T1Factory. If I do this, I cannot use the DefaultFactory class to implement DefaultT2Factory, because T2Factory is not Factory <T2>. If I add this relation to the extends T2Factory clause, I get an error that the Factory interface is used more than once. But I need a Factory interface in order to be able to use the create method in the default implementation.
In terms of method signatures, everything is fine. As a result, I have to duplicate the default implementation implementation into the Factory implementation. In my case, this encoding is quite large, and I want to avoid code duplication.
Any idea how to get around this problem.