So I have a class, AbtractParent, and an arbitrary amount of subclasses which extend it.
Each subclass has a string associated with it.
Eventually, I want to be able to write code along the lines of
if(AbstractParent.doesStringRepresentSubClass("example String"))
AbstractParent.getInstOfSubClassReppedBy("example String");
My current solution is to store a map as a static variable of AbstractParent and have each subclass add an instance of itself and its string to this map.
The problem is that by doing this, AbstractParent now has knowledge of every one of its subclasses, which seems contrary to the ideas of OOP.
My only other solution ideas are
Is their a better, more OOP proper design way of doing this?
Thanks all!
Edit 1: The string representation WILL NOT be the same as the class name and thus cannot be cast to a Type using reflection.
Edit 2: The end goal here is to follow the Open Close principle and thus the creation of a subclass should require editing only the subclass file. Due to this a factory method can't be used to solve the problem entirely.
That said, separating my above code into both a factory class and an abstract parent class is definitely good design that I will implement.
This looks to me like you're trying to implement a factory method.
Your factory method would have a knowledge of each subclass and how to instantiate it given a string. Note that this knowledge doesn't reside in the base class of the objects you're creating.
e.g.
public class Factory {
public AbstractParent newInstance(String spec) {
if ("example String".equals(spec)) {
return new ExampleStringSubclass();
}
// etc.
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With