jeudi 25 février 2016

Instantiate an extended class or its parent (depending on circumstances)

Let's say I have a class named Human in ProjectA. It is instantiated in the CreatureBuilder class of the same project.

Now I want to create a new class called Cyborg in a different project, i.e. in ProjectB. ProjectB has ProjectA in its imports, but ProjectA knows nothing about ProjectB.

Cyborg extends Human, and must also be instantiated by CreatureBuilder of ProjectA (so, Cyborg is located in ProjectB, I call CreatureBuilder from ProjectB to instantiate Cyborg, but CreatureBuilder is located in ProjectA, as well as my Human class).

I need a logic to create a Human when CreatureBuilder is instantiated from ProjectA, and to create a Cyborg when CreatureBuilder is instantiated from ProjectB.

I think it is achievable by creating an interface with a getCreature() method in ProjectA. This method will be overridden in ProjectB to return new Cyborg and then pass it back to CreatureBuilder of ProjectA. Any other suggestions? What do you think is the best workaround? Can I use reflection API instead?

Cheers!

Aucun commentaire:

Enregistrer un commentaire