|
| 1 | +from abc import ABC, abstractmethod |
| 2 | + |
| 3 | +# Bad example |
| 4 | +# class Printer(ABC): |
| 5 | +# """Printer interface.""" |
| 6 | + |
| 7 | +# @abstractmethod |
| 8 | +# def print(self, document): |
| 9 | +# pass |
| 10 | + |
| 11 | +# @abstractmethod |
| 12 | +# def fax(self, document): |
| 13 | +# pass |
| 14 | + |
| 15 | +# @abstractmethod |
| 16 | +# def scan(self, document): |
| 17 | +# pass |
| 18 | + |
| 19 | + |
| 20 | +# class OldPrinter(Printer): |
| 21 | +# """Old printer, concrete implementation.""" |
| 22 | + |
| 23 | +# def print(self, document): |
| 24 | +# print(f"Print {document} in black and white") |
| 25 | + |
| 26 | +# def fax(self, document): |
| 27 | +# raise NotImplementedError("Fax functionality not supported") |
| 28 | + |
| 29 | +# def scan(self, document): |
| 30 | +# raise NotImplementedError("Scan functionality not supported") |
| 31 | + |
| 32 | + |
| 33 | +# class ModernPrinter(Printer): |
| 34 | +# """Modern printer, concrete implementation.""" |
| 35 | + |
| 36 | +# def print(self, document): |
| 37 | +# print(f"Printing {document} in color") |
| 38 | + |
| 39 | +# def fax(self, document): |
| 40 | +# print(f"Faxing {document}") |
| 41 | + |
| 42 | +# def scan(self, document): |
| 43 | +# print(f"Scanning {document}") |
| 44 | + |
| 45 | + |
| 46 | +# Good example |
| 47 | +class Printer(ABC): |
| 48 | + """Printer interface.""" |
| 49 | + |
| 50 | + @abstractmethod |
| 51 | + def print(self, document): |
| 52 | + pass |
| 53 | + |
| 54 | + |
| 55 | +class Fax(ABC): |
| 56 | + """Fax interface.""" |
| 57 | + |
| 58 | + @abstractmethod |
| 59 | + def fax(self, document): |
| 60 | + pass |
| 61 | + |
| 62 | + |
| 63 | +class Scan(ABC): |
| 64 | + """Scan interface.""" |
| 65 | + |
| 66 | + @abstractmethod |
| 67 | + def scan(self, document): |
| 68 | + pass |
| 69 | + |
| 70 | + |
| 71 | +class OldPrinter(Printer): |
| 72 | + """Old printer, concrete implementation.""" |
| 73 | + |
| 74 | + def print(self, document): |
| 75 | + print(f"Print {document} in black and white") |
| 76 | + |
| 77 | + |
| 78 | +class NewPrinter(Printer, Fax, Scan): |
| 79 | + """New printer, concrete implementation.""" |
| 80 | + |
| 81 | + def print(self, document): |
| 82 | + print(f"Printing {document} in color") |
| 83 | + |
| 84 | + def fax(self, document): |
| 85 | + print(f"Faxing {document}") |
| 86 | + |
| 87 | + def scan(self, document): |
| 88 | + print(f"Scanning {document}") |
| 89 | + print(f"Scanning {document}") |
0 commit comments