Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Abstract Class needs to know all Extending Classes?

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

  1. have a config file where every sub class writes its class name and string representation
  2. every time i create a subclass, add a line of code to an if-else statement inside of the doesStringRepresentSubClass .

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.

like image 402
djs22 Avatar asked Jun 05 '26 22:06

djs22


1 Answers

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.
   }
}
like image 128
Brian Agnew Avatar answered Jun 07 '26 12:06

Brian Agnew