Skip to content

Instantly share code, notes, and snippets.

@inesp
Last active October 20, 2019 08:18
Show Gist options
  • Save inesp/44ef0e01989f7af8e7f9b474e88df6fd to your computer and use it in GitHub Desktop.
Save inesp/44ef0e01989f7af8e7f9b474e88df6fd to your computer and use it in GitHub Desktop.
# We create dedicated pizza maker classes, each class
# creates just 1 type of pizza.
# We will also register the makers.
@register_pizza_maker
class _PizzaMargheritaMaker:
pizza_class_name = "PizzaMargherita"
def create(with_bazil=True):
pizza = PizzaMargherita(with_bazil=True)
.... <populate all the other fields>
return pizza
@register_pizza_maker
class _PizzaPestoMaker:
pizza_class_name = "PizzaPesto"
def create(cheeze_type, with_arugula=True):
...
class PizzaMaker:
# We will again promote "ptype" and name it explicitly.
def create_pizza(self, ptype, **pizza_properties):
# get_pizza_makers will also raise UnknownPizaType if needed
pizza_maker = get_pizza_makers(ptype)
# The actual pizza maker will validate pizza_properties
pizza = pizza_maker.create(**pizza_properties)
return pizza
# This will be our registry of all existing pizza makers
ALL_PIZZA_MAKERS = {}
# With this decorator, we will register Maker classes
def register_pizza_maker(maker_class):
if maker_class.pizza_class_name is None:
raise ValueError("Missing pizza_class_name for pizza maker %s" % maker_class.__name__)
ALL_PIZZA_MAKERS[maker_class.pizza_class_name] = maker_class
return maker_class
# With this getter function, we will resolve pizza class names to pizza makers.
def get_pizza_maker(pizza_type: str):
maker = ALL_PIZZA_MAKERS.get(pizza_type)
if maker is None:
raise UnknownPizaType(pizza_type)
return maker
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment