How do i use the same factory method for a subclass?
I need a object B, but i get a object A when i execute 'B.GetByID()'
public class A
{
public A()
{
}
public static A GetSelf()
{
return new A();
}
public static A GetByID()
{
return GetSelf();
}
}
public class B extends A
{
public B()
{
super();
}
开发者_开发技巧
public static B GetSelf()
{
return new B();
}
}
B.GetByID(); //returns A, i need B
You can only do that by also creating a B GetByID()
method in B
. That's somewhat ugly though...
Basically your B.GetByID()
call will be resolved to A.GetByID()
; nothing in the compiled code will indicate that it was originally B.GetByID()
, and the call to GetSelf()
within GetByID()
will be resolved to A.GetSelf()
anyway.
Basically, static methods don't allow for polymorphism in the way you want. I suggest you create an AFactory
and a BFactory
subclass, and use method overriding in the normal way, with instance methods.
You could add a GetByID
method to B
, like so:
public class B ... {
public static B GetByID()
{
return GetSelf();
}
}
Your factory method (no matter in which class it's declared) needs to be aware of both, A
and B
and then make a decision on which class to instantiate. If the caller knows it needs a B
, it just can do a new B()
anyway, so the factory method has no value there anyway.
精彩评论