Pizza Builder Example

Ben Fagin edited this page Oct 31, 2013 · 8 revisions

The Pizza Builder, though a bit contrived, is useful in showcasing a simple builder. The user can select a SauceType, add cheese, and add various Toppings. A maximum of 3 toppings can be added. As well, cheese and sauce can only be added once. When the user is done, they can bake the pizza. The baking process takes time, but when finished yields a delicious Pizza object.

The descriptor:

Descriptor builder = Flapi.builder()
    .setPackage("unquietcode.tools.flapi.examples.pizza.builder")
    .setStartingMethodName("makePizza")
    .setDescriptorName("Pizza")

    .addMethod("addSauce(unquietcode.tools.flapi.examples.pizza.DisappearingPizzaExample.SauceType sauceType)").atMost(1)
    .addMethod("addCheese()").atMost(1)
    .addMethod("addTopping(unquietcode.tools.flapi.examples.pizza.DisappearingPizzaExample.Topping topping)").atMost(3)
    .addMethod("bake()").last(Pizza.class)
.build();

And the corresponding usage:

Pizza myDeliciousPizza = PizzaGenerator.makePizza(new PizzaHelperImpl())
    .addSauce(SauceType.Marinara)
    .addTopping(Topping.Garlic)
    .addTopping(Topping.Green_Peppers)
    .addTopping(Topping.Red_Onions)
    .addCheese()
.bake();

The full source can be found here.