Re: Factory methods
On Sun, 13 May 2007 10:18:16 +0200, Jednostanicni organizam wrote:
On Sun, 13 May 2007 03:36:47 +0100, Tom Hawtin wrote:
Richard Reynolds wrote:
"Jednostanicni organizam" <jednostanicniTOCKAorganizam@gmail.com> wrote in
message news:9v38q7283927.vmycihe4x6at$.dlg@40tude.net...
Is there a way (pattern, ...) to enforce the Class B (example bellow) to
implement some factory method. Something that would have the same effect
as
the flawed example bellow.
Does someFactoryMethodToImplement have to be static? Could you make B a
singleton and use an instance method?
Then each derived class would have to have a singleton - back to the
original problem.
AFAICS, (statically) requiring a class to implement a static method
achieves nothing. The only use I could think for this is if reflection
was to be used. The first, second and third rule of using reflection is
don't chuffing well use it.
Tom Hawtin
The use for that is as follows (maybe it can be achived in some other way):
We have the next:
A interface that every B,X,.. if they want to be A have to implement.
class Box<E extends A> that can contain any element of type B, X, ...
class Box has method getABoxOfSomeNiceA() { .. } so that method would have
to ask B or X what is the nice B or X. And it would do so by calling the
B.someFactoryMethodToImplement().
So if someFactoryMethodToImplement() is not enforced by A to be implemented
by subclasses, Box will not be able to return a result of
getABoxOfSomeNiceA() because maybe that implementation of A ,it is using,
doesn't have that method implemented.
The only way to do it, as it seems is to give up on A being an interface
and to make it an abstract class. I don't like it :) but here is the idea.
public abstract class A {
public enum Special { NICE, NOT_NICE; }
protected A() {}
public A(A.Special special) {}
public abstract void methodToImplement(A a);
}
public class B extends A {
public B (A.Special special) {
if(special == Special.NICE) {
// make nice B
} else if (special == Special.NOT_NICE){
// make not nice B
} else {
throw new IllegalArgumentException();
}
}
public void methodToImplement(A a) { ... }
}