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
keep
BaseClass
in 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.