from abc import ABC, abstractmethod
class GateState(ABC):
@abstractmethod
def insert_coin(self, gate):
pass
@abstractmethod
def pass_through(self, gate):
pass
class ClosedState(GateState):
def insert_coin(self, gate):
print("Coin inserted. Gate is opening.")
gate.set_state(OpenState())
def pass_through(self, gate):
print("Gate is closed. Please insert a coin.")
class OpenState(GateState):
def insert_coin(self, gate):
print("Gate is already open. Please pass through.")
def pass_through(self, gate):
print("You passed through the gate. Gate is closing.")
gate.set_state(ClosedState())
class Gate:
def __init__(self):
self.state = ClosedState() # Турникет по умолчанию закрыт
def set_state(self, state):
self.state = state
def insert_coin(self):
self.state.insert_coin(self)
def pass_through(self):
self.state.pass_through(self)
def main():
gate = Gate()
# Пытаемся пройти через закрытый турникет
gate.pass_through() # Gate is closed. Please insert a coin.
# Вставляем монету, турникет открывается
gate.insert_coin() # Coin inserted. Gate is opening.
# Пытаемся вставить монету снова, пока турникет открыт
gate.insert_coin() # Gate is already open. Please pass through.
# Проходим через турникет, он закрывается
gate.pass_through() # You passed through the gate. Gate is closing.
# Повторим попытку пройти через закрытый турникет
gate.pass_through() # Gate is closed. Please insert a coin.
main()
Gate is closed. Please insert a coin.
Coin inserted. Gate is opening.
Gate is already open. Please pass through.
You passed through the gate. Gate is closing.
Gate is closed. Please insert a coin.