中介模式
中介模式,類似於房屋中介的存在,用一個對象來封裝一系列的對象交互。
解決問題:類圖中出現了網狀結構,且交互實現比較複雜時,可以考慮將類圖設計成星型結構。以達到減少類與類的依賴,降低耦合的目的。
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()
對這個模式理解不太完整,先就這樣