|
| 1 | +""" |
| 2 | +EN: Adapter Design Pattern |
| 3 | +
|
| 4 | +Intent: Provides a unified interface that allows objects with incompatible |
| 5 | +interfaces to collaborate. |
| 6 | +
|
| 7 | +RU: Паттерн Адаптер |
| 8 | +
|
| 9 | +Назначение: Позволяет объектам с несовместимыми интерфейсами работать вместе. |
| 10 | +""" |
| 11 | + |
| 12 | + |
| 13 | +class Target: |
| 14 | + """ |
| 15 | + EN: The Target defines the domain-specific interface used by the client |
| 16 | + code. |
| 17 | +
|
| 18 | + RU: Целевой класс объявляет интерфейс, с которым может работать клиентский |
| 19 | + код. |
| 20 | + """ |
| 21 | + |
| 22 | + def request(self) -> str: |
| 23 | + return "Target: The default target's behavior." |
| 24 | + |
| 25 | + |
| 26 | +class Adaptee: |
| 27 | + """ |
| 28 | + EN: The Adaptee contains some useful behavior, but its interface is |
| 29 | + incompatible with the existing client code. The Adaptee needs some |
| 30 | + adaptation before the client code can use it. |
| 31 | +
|
| 32 | + RU: Адаптируемый класс содержит некоторое полезное поведение, но его |
| 33 | + интерфейс несовместим с существующим клиентским кодом. Адаптируемый класс |
| 34 | + нуждается в некоторой доработке, прежде чем клиентский код сможет его |
| 35 | + использовать. |
| 36 | + """ |
| 37 | + |
| 38 | + def specific_request(self) -> str: |
| 39 | + return ".eetpadA eht fo roivaheb laicepS" |
| 40 | + |
| 41 | + |
| 42 | +class Adapter(Target, Adaptee): |
| 43 | + """ |
| 44 | + EN: The Adapter makes the Adaptee's interface compatible with the Target's |
| 45 | + interface via multiple inheritance. |
| 46 | +
|
| 47 | + RU: Адаптер делает интерфейс Адаптируемого класса совместимым с целевым |
| 48 | + интерфейсом благодаря множественному наследованию. |
| 49 | + """ |
| 50 | + |
| 51 | + def request(self) -> str: |
| 52 | + return f"Adapter: (TRANSLATED) {self.specific_request()[::-1]}" |
| 53 | + |
| 54 | + |
| 55 | +def client_code(target: "Target") -> None: |
| 56 | + """ |
| 57 | + EN: The client code supports all classes that follow the Target interface. |
| 58 | +
|
| 59 | + RU: Клиентский код поддерживает все классы, использующие интерфейс Target. |
| 60 | + """ |
| 61 | + |
| 62 | + print(target.request(), end="") |
| 63 | + |
| 64 | + |
| 65 | +if __name__ == "__main__": |
| 66 | + print("Client: I can work just fine with the Target objects:") |
| 67 | + target = Target() |
| 68 | + client_code(target) |
| 69 | + print("\n") |
| 70 | + |
| 71 | + adaptee = Adaptee() |
| 72 | + print("Client: The Adaptee class has a weird interface. " |
| 73 | + "See, I don't understand it:") |
| 74 | + print(f"Adaptee: {adaptee.specific_request()}", end="\n\n") |
| 75 | + |
| 76 | + print("Client: But I can work with it via the Adapter:") |
| 77 | + adapter = Adapter() |
| 78 | + client_code(adapter) |
0 commit comments