設計模式 策略模式 直譯器模式

2021-09-19 13:13:48 字數 4401 閱讀 4305

策略模式:

定義一系列演算法,把它們一 一封裝起來,並且使它們之間可以相互替換。此模式讓演算法的變化不會影響到使用演算法的客戶。

舉例:電商領域根據客戶的屬性或訂單中的商品計算折扣。

策略模式包含以下3個角色:context(環境類)strategy(抽象策略類)concretestrategy(具體策略類)

from abc import abc, abstractmethod

from collections import namedtuple

customer = namedtuple('customer', 'name fidelity')

class lineitem:

"""訂單中單個商品的數量和單價"""

def __init__(self, product, quantity, price):

self.product = product

self.quantity = quantity

self.price = price

def total(self):

return self.price * self.quantity

class order:

"""訂單"""

def __init__(self, customer, cart, promotion=none):

self.customer = customer

self.cart = list(cart)

self.promotion = promotion

def total(self):

if not hasattr(self, '__total'):

self.__total = sum(item.total() for item in self.cart)

return self.__total

def due(self):

if self.promotion is none:

discount = 0

else:

discount = self.promotion.discount(self)

return self.total() - discount

def __repr__(self):

fmt = '《訂單 總價: 實付: >'

return fmt.format(self.total(), self.due())

class promotion(abc): # 策略:抽象基類

@abstractmethod

def discount(self, order):

"""返回折扣金額(正值)"""

class fidelitypromo(promotion): # 第乙個具體策略

"""為積分為1000或以上的顧客提供5%折扣"""

def discount(self, order):

return order.total() * 0.05 if order.customer.fidelity >= 1000 else 0

class bulkitempromo(promotion): # 第二個具體策略

"""單個商品為20個或以上時提供10%折扣"""

def discount(self, order):

discount = 0

for item in order.cart:

if item.quantity >= 20:

discount += item.total() * 0.1

return discount

class largeorderpromo(promotion): # 第三個具體策略

"""訂單中的不同商品達到10個或以上時提供7%折扣"""

def discount(self, order):

distinct_items =

if len(distinct_items) >= 10:

return order.total() * 0.07

return 0

joe = customer('john doe', 0)

ann = customer('ann smith', 1100)

cart = [lineitem('banana', 4, 0.5),

lineitem('watermellon', 5, 5.0)]

print('策略一:為積分為1000或以上的顧客提供5%折扣')

print(order(joe, cart, fidelitypromo()))

print(order(ann, cart, fidelitypromo()))

banana_cart = [lineitem('banana', 30, 0.5),

print('策略二:單個商品為20個或以上時提供10%折扣')

print(order(joe, banana_cart, bulkitempromo()))

long_order = [lineitem(str(item_code), 1, 1.0) for item_code in range(10)]

print('策略三:訂單中的不同商品達到10個或以上時提供7%折扣')

直譯器模式:****開發者自定義一種「有內涵」的語言(或者叫字串),並設定相關的解釋規則,輸入該字串後可以輸出公認的解釋,或者執行程式可以理解的動作。這種模式被用在 sql 解析、符號處理引擎等

直譯器模式要實現兩個核心角色:

終結符表示式:實現與文法中的元素相關聯的解釋操作,通常乙個直譯器模式中只有乙個終結符表示式,但有多個例項,對應不同的終結符。終結符一半是文法中的運算單元,比如有乙個簡單的公式r=r1+r2,在裡面r1和r2就是終結符,對應的解析r1和r2的直譯器就是終結符表示式

非終結符表示式:文法中的每條規則對應於乙個非終結符表示式,非終結符表示式一般是文法中的運算子或者其他關鍵字,比如公式r=r1+r2中,+就是非終結符,解析+的直譯器就是乙個非終結符表示式。非終結符表示式根據邏輯的複雜程度而增加,原則上每個文法規則都對應乙個非終結符表示式。

何時使用:如果一種特定型別的問題發生的頻率足夠高,那麼可能就值得將該問題的各個例項表述為乙個簡單語言中的句子。這樣就可以構建乙個直譯器,該直譯器通過解釋這些句子來解決該問題。

應用例項:編譯器、運算表示式計算。

優點: 1、可擴充套件性比較好,靈活。 2、增加了新的解釋表示式的方式。 3、易於實現簡單文法。

缺點: 1、可利用場景比較少。 2、對於複雜的文法比較難維護。 3、直譯器模式會引起類膨脹。

"""實現一段簡單的中文程式設計"""

import time

import datetime

class code:

"""自定義語言"""

def __init__(self, text=none):

self.text = text

class interpreterbase:

"""自定**釋器基類"""

def run(self, code):

pass

class interpreter(interpreterbase):

"""實現直譯器方法,實現終結符表示式字典"""

def run(self, code):

code = code.text

code_dict =

print(code_dict.get(code))

if __name__ == '__main__':

test = code()

test.text = '獲取當前時間戳'

data1 = interpreter().run(test)

test.text = '獲取當前日期'

ps:歡迎補充和指正

設計模式 直譯器模式

未來機器智慧型化已然成為趨勢,現在手機都能聽懂英語和普通話,那我大中華幾萬種方言的被智慧型化也許也是趨勢,我們的方言雖然和普通話相似,但是還是不一樣的。這可能需要乙個新的語法分析器來幫助我們。我們的直譯器模式就是描述了如何為簡單的語言定義乙個文法,如何在該語言中表示乙個句子,以及如何解釋這些句子。但...

設計模式 直譯器模式

直譯器模式 給定乙個語言,定義它的文法的一種表示,並定義乙個直譯器,這個直譯器使用該表示來解釋語言中的句子。如果一種特定型別的問題發生的頻率足夠高,那麼可能就值得將該問題的各個例項表述為乙個簡單語言中的句子。這樣就可以構建乙個直譯器,該直譯器通過解釋這些句子來解決該問題。當有乙個語言需要解釋執行,並...

設計模式 直譯器模式

直譯器模式 interpreter pattern 提供了評估語言的語法或表示式的方式,它屬於行為型模式。這種模式實現了乙個表示式介面,該介面解釋乙個特定的上下文。這種模式被用在 sql 解析 符號處理引擎等。給定乙個語言,定義它的文法表示,並定義乙個直譯器,這個直譯器使用該標識來解釋語言中的句子。...