The following code works very well when all involved classes are in the same project (determineSubClass is a member of BaseClass):
protected static BaseClass determineSubClass(String p1, int p2, Boolean p3) {
BaseClass baseObj = null;
if ( (baseObj = SubClassOne.ofType(p1, p2, p3)) != null )
return baseObj;
else if ( (baseObj = SubClassTwo.ofType(p1, p2, p3)) != null )
return baseObj;
else if ( (baseObj = SubClassThree.ofType(p1, p2, p3)) != null )
return baseObj;
else if ( (baseObj = SubClassFour.ofType(p1, p2, p3)) != null )
return baseObj;
else
return new SubClassDefault(p1, p2, p3);
}
But now, I want to move the BaseClass to a shared Library project, in which SubClassOne, SubClassTwo, SubClassThree and SubClassFour are not defined in the library but rather in the applications using this library.
I could of course move BaseClass back to each and every application using this library, but I wonder:
- Is there a better solution?
- Is there a solution that would let me
keepBaseClassin the Library
project and eliminate the need for it
to know about all superclasses
derived from it?
EDIT (answering @ahmet alp balkan question below):
ofType() of each subclass does 2 things:
- Determines, based on the content of
String p1 and the other parameters
p2 and p3, whether the subclass to
be instantiated is of its type. - If the answer is positive, it
instantiates an object of self
subclass. Otherwise, returns null.
As for your second question, BaseClass at this point holds common data members and methods to all subclasses and only this single static method which is aimed at delegating the responsibility of determining subclass to be instantiated.
BTW, thanks to your question I noticed a horrible typo in my original post: “SuperClassOne” should be “SubClassOne” etc.
Your static
determineSubClassmethod is a factory method. It should obviously not be located on theBaseClass, since not only the base class should not know anything about the subclasses, but in your case it can’t know anything about it, since you want to locate the base class in another project. No, this method should be located in a factory class that is responsible for creatingBaseClassinstances. What you should do is define an interface (or base type) for creatingBaseClassinstances next to theBaseTypeand defines an implementation in the composition root of your application. When you have multiple applications, they probably each have a different set ofBaseClasssub types, so each application will have a different factory. When you have this construction in place, you can inject the factory into classes that needBaseClassinstances.It might look something like this: