Pseudo-Backwards Builder Pattern?
In a legacy codebase I have a very large class with far too many fields/responsibilities. Imagine this is a Pizza object.
It has highly granular fields like:
- hasPepperoni
- hasSausage
- hasBellPeppers
I know that when these three fields are true, we have a Supreme pizza. However, this class is not open for extension or change, so I can't add a PizzaType, or isSupreme(), etc. Folks throughout the codebase duplicate the same if(a && b && c) then isSupreme)
logic all over place. This issue comes up for quite a few concepts, so I'm looking for a way to deconstruct this object into many subobjects, e.g. a pseudo-backwards Builder Pattern.
PizzaType pizzaType = PizzaUnbuilder.buildPizzaType(Pizza); //PizzaType.SUPREME
Dough d开发者_JAVA百科ough = PizzaUnbuilder.buildDough(Pizza);
Is this the right approach? Does this pattern exist already?
How about the Adapter Pattern?
Basically a wrapper class that has all the functionality you really want which can go easily back and forth to a Pizza class.
MenuPizza myPizza = new MenuPizza(pizza);
PizzaType pizzaType = myPizza.getPizzaType();
DoughType doughType = myPizza.getDoughType();
And you could provide the reverse functionality...
MenuPizza otherPizza = new MenuPizza(PizzaType.SUPREME, DoughType.SOUR);
Pizza pizzaPOJO = otherPizza.getPizzaPOJO();
I think this would be a great use case for extension functions, which don't exist in java. In lieu of that the simplest solution in my mind is to create a class and add the methods that would be extensions into that utility class as static methods; PizzaUtils.isSupreme(Pizza pizza)
.
精彩评论