什么是策略模式?
在Python中,除了上次介紹的工廠模式,還有一種應用廣泛的設計模式,即策略模式,策略模式就是一個策略類,它可以用相同的介面來呼叫不同的策略類,從而實作不同策略下的演算法,
策略模式一般由三個部分組成:
Context:背景關系類,持有具體策略類的實體,并負責呼叫相關的演算法Strategy:策略抽象類,用來約束一系列的策略演算法(Context 使用這個介面來呼叫具體的策略實作演算法)ConcreateStrategy:具體的策略類(繼承抽象策略類)
何時選擇策略模式?
如果一件事的行為可以在不同的環境下有不同的表現,那么就可以使用策略模式,
舉個例子:
比如APP的分享,它可以是微信分享,QQ分享,微博分享,各種分享所要輸出的內容不一樣,所以可以使用策略模式來實作不同的分享,
再比如出門旅游,可以自駕、坐高鐵、坐飛機,這種屬于出行策略,
策略模式的應用
今天分享的策略模式應用場景是線上網購折扣場景,
日常網購各種折扣,禮金,滿減等等折扣場景十分廣泛,這些折扣可以用策略模式來實作,
我們遵循策略模式的三個部分來展開這次需求:
Context
背景關系類,持有具體策略類的實體,并負責呼叫相關的演算法
class Customer:
"""顧客類"""
def __init__(self, name, integral, is_vip):
self.name = name
self.integral = integral
self.is_vip = is_vip
def __repr__(self):
return self.name
class Goods:
"""商品類"""
def __init__(self, name, price, num):
self.name = name
self.price = price
self.num = num
def total(self):
return self.price * self.num
class Order:
"""
訂單類
關聯上用戶、對應的商品、折扣策略
通過折扣策略來計算訂單的實際價格
"""
def __init__(self, customer, promotion=None):
"""
:param customer: 顧客物件
:param promotion: 折扣策略物件
"""
self.cart = [] # 購物車
self.customer = customer # 客戶資訊
self.promotion = promotion # 具體的折扣策略
def add_cart(self, *good):
"""商品加入購物車"""
self.cart += good
def total(self):
"""計算購物車商品總價"""
return sum(map(lambda x: x.total(), self.cart))
def due(self):
"""計算商品具體折扣后價格"""
if self.promotion is None:
return self.total()
return self.total() - self.promotion.discount(self)
def __repr__(self):
return f"<{self.customer} Order total:{self.total()} due:{self.due()}>"
Strategy
策略抽象類,用來約束一系列的策略演算法,
class Promotion(ABC):
"""折扣策略基類"""
def discount(self, order):
"""計算折扣后的價格"""
raise NotImplementedError
未來我們具體實作的折扣策略必須是繼承自Promotion的子類,并實作discount方法,
ConcreateStrategy
具體的折扣策略
class NoPromotion(Promotion):
"""不打折"""
def discount(self, order):
return 0
class RatePromotion(Promotion):
"""按比例打折"""
def __init__(self, rate):
self.rate = rate
def discount(self, order):
return order.total() * (1 - self.rate)
可以觀察到,我們使用Promotion作為子類的約束,而RatePromotion是具體的折扣策略,
通過Order類來協同消費者、商品、折扣策略,實作訂單的折扣計算,
# 創建三個商品
good1 = Goods('apple', 10, 1)
good2 = Goods('banana', 20, 2)
good3 = Goods('orange', 30, 3)
# 創建一個消費者
customer = Customer('米樂', 100, False)
# 將消費者和折扣系結到訂單上
order = Order(
customer=customer,
promotion=RatePromotion(0.8)
)
# 將商品添加到訂單中
order.add_cart(good1, good2, good3)
print(order)
# <米樂 Order total:140 due:112.0>
有一天領導又準備搞一個滿100減10的活動,我們可以這樣來實作:
class FullReductionPromotion(Promotion):
"""滿減"""
def __init__(self, full, reduction):
self.full = full
self.reduction = reduction
def discount(self, order):
return order.total() // self.full * self.reduction
order = Order(
customer=customer,
promotion=FullReductionPromotion(100, 10)
)
print(order)
# <米樂 Order total:140 due:130>
以上就是筆者對策略模式的理解及應用場景的實作,
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/547035.html
標籤:設計模式
下一篇:python策略模式場景
