[Python] 中介模式

中介模式

中介模式,類似於房屋中介的存在,用一個對象來封裝一系列的對象交互。

解決問題:類圖中出現了網狀結構,且交互實現比較複雜時,可以考慮將類圖設計成星型結構。以達到減少類與類的依賴,降低耦合的目的。

class Consumer:
    "消費者"
    def __init__(self,product, price):
        self.name = "買家"
        self.product = product
        self.price = price

    def shopping(self,name):
        "買東西"
        print("{}向{}購買{}產品: 價格{}元".format(self.name,name,self.product, self.price))


class Producer:
    "生產者"
    def __init__(self, product, price):
        self.name = "賣家"
        self.product = product
        self.price = price

    def sale(self,name):
        "賣東西"
        print("{}向{}銷售{}產品: 價格{}元".format(self.name, name, self.product, self.price))

class Mediator:
    "中介"
    def __init__(self):
        self.name = "中介"
        self.consumer = None
        self.producer = None

    def sale(self):
        "把東西倒騰給買家"
        self.consumer.shopping(self.name)

    def shopping(self):
        "跟賣家收過來"
        self.producer.sale(self.name)

    def profit(self):
        print("中介賺了{}元".format(self.consumer.price - self.producer.price))

    def complete_trade(self):
        self.shopping()
        self.sale()
        self.profit()

if __name__ == '__main__':
    consumer = Consumer("手機",1999)
    producer = Producer("手機",1800)
    mediator = Mediator()
    mediator.consumer = consumer
    mediator.producer = producer
    mediator.complete_trade()

對這個模式理解不太完整,先就這樣

發佈了18 篇原創文章 · 獲贊 41 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章