In the last lesson, you stacked two cooperative layers onto the kit, and the drilling kit now describes itself as audit[tag[KIT-17: drilling]]. The checkout desk wants that description on a printed label. Your first thought might be one more layer that adds printLabel() to every kit. But a kit isn’t a printer, and the desk may want a different printer tomorrow.
In this lesson, you’ll keep the printer separate and store it in another object. Start with the Python version.
Hold the Printer in a Property
In Python, you’d keep printing as a separate job. A LabelPrinter turns a kit into a label, and a LabelStation keeps a printer in an attribute and forwards each request to it:
class LabelPrinter:
def print_label(self, kit):
return f"PRINT {kit.describe()}"
class LabelStation:
def __init__(self, printer):
self.printer = printer
def print_label(self, kit):
return self.printer.print_label(kit)
Given the composed drilling kit, LabelStation(LabelPrinter()).print_label(drilling) returns PRINT audit[tag[KIT-17: drilling]]. The station never checks its printer’s class. It only calls print_label() on whatever it was given.