I have an abstract class, AbstractClass
which ultimately superclasses a large number of final
concrete classes A
, B
, C
etc. "Ultimately" as in some cases there is an intermediate abstract class - D1
and D2
both extend AbstractD
which extends AbstractClass
, for example. At the time of object creation, each one of those concrete classes will need to be linked to one (and only one) instance of one of the concrete classes: possibly the same class, possibly a different one. Each concrete class also has a large number of constructors.
Coding this as:
public A(String aVariable, int anotherVariable, AbstractClass objectToBeLinked){
//do some stuff with other variables;
owner = objectToBeLinked;
objectToBeLinked.addToInventory(this);
}
and then other constructor signatures as needed will give me a Leaking this in Constructor
While I understand that that isn't necessarily a flaw, I would like to avoid it - for thread safety and also just to use best practices. The best solution I can see is to implement some form of factory method:
public static void createObjectA(String aVariable, int anotherVariable, AbstractClass objectToBeLinked){
a = new A(String aVariable, int anotherVariable, AbstractClass objectToBeLinked);
objectToBeLinked.addToInventory(a);
}
(for example - implementation could obviously vary) to ensure that object creation is finished before it is linked. However, given the large number of concrete classes and the large number of constructors each has, that would mean creating a huge amount of factory methods. If that is the best solution, then so be it but I'm wondering if there is a better method I'm not seeing.