43 lines
1019 B
Python
43 lines
1019 B
Python
"""
|
|
实例:
|
|
汤宝宝成为了收银员,消费者可以使用现金或者支付宝支付。
|
|
"""
|
|
|
|
from abc import ABC, abstractmethod
|
|
|
|
|
|
class Strategy(ABC):
|
|
@abstractmethod
|
|
def pay(self, amount: float) -> str:
|
|
pass
|
|
|
|
|
|
class CashPayment(Strategy):
|
|
def pay(self, amount: float) -> str:
|
|
return(f"使用现金支付了 {amount:.2f} 元。")
|
|
|
|
|
|
class AlipayPayment(Strategy):
|
|
def pay(self, amount: float) -> str:
|
|
return(f"使用支付宝支付了 {amount:.2f} 元。")
|
|
|
|
|
|
class Context:
|
|
strategy: Strategy
|
|
|
|
def set_strategy(self, strategy: Strategy) -> None:
|
|
self._strategy = strategy
|
|
|
|
def pay(self, amount: float) -> str:
|
|
return self._strategy.pay(amount)
|
|
|
|
if __name__ == "__main__":
|
|
print("=========== 策略模式 ===========")
|
|
|
|
context = Context()
|
|
context.set_strategy(CashPayment())
|
|
print(context.pay(100.0))
|
|
context.set_strategy(AlipayPayment())
|
|
print(context.pay(200.0))
|
|
|
|
print("\n========= 策略模式结束 =========") |