mercredi 29 avril 2020

Allow instantiate of specific variables of a class based on the variable value

I have a use case where I have to instantiate a given class with only specific variables based on the value of variable (let say in this example) typeName. For a variable String typeName, if its value is TYPE-1, only specific set of variables (a,b,c) should be allowed to be instantiate. Similarly if its value is TYPE-2, only the another set of variables (x,y,z) should be allowed to instantiate.

if(typeName == "TYPE1") 
 {
     CentralClass class = new CentralClass(a,b,c);  //initiating only variable a,b,c
 }
else
{  
     CentralClass class = new CentralClass(x,y,z);  //initiating only variable x,y,z
}

Class Structure

public class CentralClass {

 String typeName; //ALLOWED Values TYPE1, TYPE2
 String x;
 String y;
 String z;

 String a;
 String b;
 String c;
}

What would be the best way to do so via any design pattern etc.

Note: The structure of the class is open for change. We can have multiple classes(clubbing different variables), inner, static classes, or any design pattern enforced etc.

Aucun commentaire:

Enregistrer un commentaire