將其他對象之間的交互裝在中介者對象中,達(dá)到松耦合、隱式引用、獨(dú)立變化,與代理模式有相似之感《python設(shè)計模式(十一):代理模式模式》,但是代理模式是結(jié)構(gòu)性模式,側(cè)重于對對象調(diào)用的接口控制,而中介者模式是行為性模式,解決對象與對象之間相互調(diào)用的行為問題。
我們以生產(chǎn)者和消費(fèi)者之間的銷售作為一個中介者,用對象來表示生產(chǎn)和購買及流通這個過程。
class Consumer:
"""消費(fèi)者類"""
def __init__(self, product, price):
self.name = "消費(fèi)者"
self.product = product
self.price = price
def shopping(self, name):
"""買東西"""
print("向{} 購買 {}價格內(nèi)的 {}產(chǎn)品".format(name, self.price, self.product))
class Producer:
"""生產(chǎn)者類"""
def __init__(self, product, price):
self.name = "生產(chǎn)者"
self.product = product
self.price = price
def sale(self, name):
"""賣東西"""
print("向{} 銷售 {}價格的 {}產(chǎn)品".format(name, self.price, self.product))
class Mediator:
"""中介者類"""
def __init__(self):
self.name = "中介者"
self.consumer = None
self.producer = None
def sale(self):
"""進(jìn)貨"""
self.consumer.shopping(self.producer.name)
def shopping(self):
"""出貨"""
self.producer.sale(self.consumer.name)
def profit(self):
"""利潤"""
print('中介凈賺:{}'.format((self.consumer.price - self.producer.price )))
def complete(self):
self.sale()
self.shopping()
self.profit()
if __name__ == '__main__':
consumer = Consumer('手機(jī)', 3000)
producer = Producer("手機(jī)", 2500)
mediator = Mediator()
mediator.consumer = consumer
mediator.producer = producer
mediator.complete()
# 向生產(chǎn)者 購買 3000價格內(nèi)的 手機(jī)產(chǎn)品
# 向消費(fèi)者 銷售 2500價格的 手機(jī)產(chǎn)品
# 中介凈賺:500
使用場景: 1、系統(tǒng)中對象之間存在比較復(fù)雜的引用關(guān)系,導(dǎo)致它們之間的依賴關(guān)系結(jié)構(gòu)混亂而且難以復(fù)用該對象。 2、想通過一個中間類來封裝多個類中的行為,而又不想生成太多的子類。
注意事項:不應(yīng)當(dāng)在職責(zé)混亂的時候使用。

image