Intermediary model , Install the interaction between other objects in the mediator object , To achieve loose coupling 、 Implicitly quote 、 Independent change .
There are similarities between the intermediary model and the agent model . But the agency model is a structural model , Focus on the interface control of object calls ; The mediator model is a behavioral model , Solve the behavior problem of calling each other between objects .
Take the sales between producers and consumers as an intermediary , Use objects to express the process of production, purchase and circulation .
class Consumer:
""" Consumer class """
def __init__(self, product, price):
self.name = " consumer "
self.product = product
self.price = price
def shopping(self, name):
""" To buy things """
print(" towards {} Buy {} Within the price {} product ".format(name, self.price, self.product))
class Producer:
""" Producer class """
def __init__(self, product, price):
self.name = " producer "
self.product = product
self.price = price
def sale(self, name):
""" Selling goods """
print(" towards {} sales {} Price {} product ".format(name, self.price, self.product))
class Mediator:
""" Intermediary class """
def __init__(self):
self.name = " Intermediary "
self.consumer = None
self.producer = None
def sale(self):
""" Stock purchase """
self.consumer.shopping(self.producer.name)
def shopping(self):
""" shipment """
self.producer.sale(self.consumer.name)
def profit(self):
""" profits """
print(' Intermediary net income :{}'.format((self.consumer.price - self.producer.price )))
def complete(self):
self.sale()
self.shopping()
self.profit()
if __name__ == '__main__':
consumer = Consumer(' mobile phone ', 3000)
producer = Producer(" mobile phone ", 2500)
mediator = Mediator()
mediator.consumer = consumer
mediator.producer = producer
mediator.complete()