Advanced OOP and patterns · 10 / 15 Exercise Medium

Factory with a class registry

Objective

A factory creates objects from a name. With a registry (a dictionary) and a decorator, each class registers itself, and the factory does not need a chain of if/elif.

Instructions

  • Create a decorator @register(name) that stores the class in a dictionary REGISTRY, and register Dog (dog), Cat (cat) and Cow (cow) with the attribute sound.
  • Read n and then n names. For each one create the animal and show name: sound; if the name is not registered, show Unknown type: name.
Input
3
dog
cow
fish
Output
dog: woof
cow: moo
Unknown type: fish

Open the editor in full screen: the statement on the left and your code, the output and the tests on the right.

Start exercise