vendredi 30 septembre 2016

How to instantiate proper implementation in JAVA based on real time data stored in parameter?

I am rewriting old JAVA code that is obsolete and I am trying to do it the best way and to learn something new. Basically I am not a skilled JAVA programmer but I know some stuff.

The problem: Piece of code is responsible for creation of some objects (let's call them products). I want to use factories and reflection to keep future updates easy - factories will be supposed to find implementation of specific interface and to get the instance of that implementation..

So I have s Create interface with create method that accepts some JSON data to give them to the object that is being created. So far everything is OK.

Recently I realized that sometimes the actual Product that should be created is dependent on real data stored in that JSON. E.g. if the product_type is "B" it has to create instance of ProductB instead of ProductA (default).

I am looking for a simple solution that would keep simple usage of one Create interface and no future updates in interfaces and factories but I need to be able add more types of product. The only thing I found as a solution would be reflection and some implementation class name vs. product type (as a string) matching rule.

I am using JAVA 8.

Any idea please?





Aucun commentaire:

Enregistrer un commentaire