Facebook Pixel

Exercise: Builder

This exercise puts the Builder pattern into code. You will implement a pizza builder that accumulates configuration through setter-style methods and produces the finished object only when build is called.

Scenario

A pizza configuration session receives a sequence of commands. Only the build command produces output; the others configure the builder silently and return the builder itself so calls can be chained.

Commands

The program reads a list of commands, one per line, and prints one line of output for each build command.

CommandBehaviorOutput
["new"]Reset the builder to a clean slate for the next pizza(none)
["size", s]Set the pizza size to small, medium, or large(none)
["top", name]Add a topping; multiple toppings accumulate in order(none)
["build"]Assemble and describe the pizza"Pizza: <size>, toppings: <comma-joined toppings>", or "Pizza: <size>, toppings: none" if no toppings were added

If no size command was issued before build, the default size is medium.

Example
Input
7
size large
top pepperoni
top mushrooms
build
new
top olives
build
Output
Pizza: large, toppings: pepperoni, mushrooms
Pizza: medium, toppings: olives
Explanation
The first sequence sets size to large, adds two toppings, then calls build. The `new` command resets the builder to a clean slate with default size "medium". The second sequence adds one topping without setting a size, so the built pizza uses the default. Toppings are listed in the order they were added.

Your task

Fill in set_size, add_topping, and build on PizzaBuilder, and __str__ on Pizza, so the build command produces the output above.

Invest in Yourself
Your new job is waiting. 83% of people that complete the program get a job offer. Unlock unlimited access to all content and features.
Go Pro