59 lines
1.7 KiB
Python
59 lines
1.7 KiB
Python
"""
|
|
实例:
|
|
汤宝宝买火车票,可以去火车站买,也可以去代售点买,但是汤宝宝选择全都要。然而,火车站总共只剩两张票,这可苦了小明了。
|
|
"""
|
|
|
|
from abc import ABC, abstractmethod
|
|
|
|
|
|
class Seller(ABC):
|
|
@abstractmethod
|
|
def sell(self, name: str) -> bool:
|
|
pass
|
|
|
|
|
|
class TrainStation(Seller):
|
|
stock: int
|
|
|
|
def __init__(self, stock: int) -> None:
|
|
print(f"火车站库存{stock}张票")
|
|
self.stock = stock
|
|
|
|
def sell(self, name: str) -> bool:
|
|
print(f"{name}去火车站买票。")
|
|
if self.stock > 0:
|
|
self.stock -= 1
|
|
print(f"{name}在火车站买到一张火车票。")
|
|
return True
|
|
else:
|
|
print(f"火车站没票了,{name}没买到票。")
|
|
return False
|
|
|
|
class TicketAgency(Seller):
|
|
name: str
|
|
station: TrainStation
|
|
|
|
def __init__(self, name: str, station: TrainStation) -> None:
|
|
self.name = name
|
|
self.station = station
|
|
|
|
def sell(self, name: str) -> bool:
|
|
print(f"{name}去{self.name}买票。")
|
|
result = self.station.sell(self.name)
|
|
if result:
|
|
print(f"{name}在{self.name}买到一张火车票。")
|
|
else:
|
|
print(f"{name}在{self.name}没买到票。")
|
|
return result
|
|
|
|
if __name__ == "__main__":
|
|
print("============= 代理模式 =============")
|
|
station = TrainStation(stock=2)
|
|
agency = TicketAgency(name="代售点A", station=station)
|
|
station.sell("汤宝宝")
|
|
agency.sell("汤宝宝")
|
|
print("")
|
|
agency.sell("小明")
|
|
station.sell("小明")
|
|
|
|
print("\n=========== 代理模式结束 ===========") |