certain-design-patterns/adapter.py

29 lines
1.5 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

from abc import ABC, abstractmethod
class ITransport(ABC): # Интерфейс для транспорта
@abstractmethod
def drive(self): pass
###
class Auto(ITransport): # класс машины с реализацией метода drive
def drive(self): print("Машина едет по дороге")
###
class Driver: # Класс водителя
def travel(self, transport: ITransport): transport.drive()
###
class IAnimal(ABC): # Интерфейс животного
@abstractmethod
def move(self): pass
###
class Camel(IAnimal): # Класс верблюда
def move(self): print("Верблюд идет по пескам пустыни")
###
class CamelToTransportAdapter(ITransport): # Адаптер от Camel к ITransport
def __init__(self, camel: Camel): self.camel = camel
def drive(self): self.camel.move()
driver = Driver() # Создаю путешественника
auto = Auto() # Создаю машину
driver.travel(auto) # Отправляемся в путешествие на машине (использует метод drive у транспорта)
camel = Camel() # Встретились пески, надо использовать верблюда
camel_transport = CamelToTransportAdapter(camel) # Используем адаптер, по другому реализующий метод drive
driver.travel(camel_transport) # Продолжаем путь по пескам пустыни на верблюде