jeudi 21 janvier 2016

Conditional builder pattern with dynamic parameter list

I have found Joshua Bloch builder pattern, its famous NutritionFacts example. Now I would like this builder to build two types of NutritionFacts. So lets say instead of:

NutritionFacts cocaCola = new NutritionFacts.Builder().
  calories(100).sodium(35).carbohydrate(27).build();

I would like to have something like that:

NutritionFactsA a = new NutritionFacts.Builder<NutritionFactsA>...().
  calories(100).build(); //.sodium(35).carbohydrate(27) - these are not possible to be set, when I write NutritionFactsA I cannot see these parameters

NutritionFactsB b = new NutritionFacts.Builder<NutritionFactsB>(240, 8).
  .sodium(35).build(); //here I have set only sodium value, I cannot set anything 

So is it possible in Java7 and how to do that?

Aucun commentaire:

Enregistrer un commentaire