python design pattern: mediator pattern

The interaction between other objects is installed in the mediator object to achieve loose coupling, implicit reference and independent change, which is similar to the agent pattern< python design pattern (11): agent pattern >But the agent mode is a structural mode, which focuses on the interface control of object calls, while the mediator mode is a behavioral mode, which solves the behavior problem of object calls.

We take the sales between producers and consumers as an intermediary, and use objects to represent the process of production, purchase and circulation.

class Consumer:
    """Consumer class"""

    def __init__(self, product, price): = "Consumer"
        self.product = product
        self.price = price

    def shopping(self, name):
        print("towards{} purchase {}In price {}product".format(name, self.price, self.product))

class Producer:
    """Producer class"""
    def __init__(self, product, price): = "Producer"
        self.product = product
        self.price = price

    def sale(self, name):
        """Selling goods"""
        print("towards{} Sale {}Price {}product".format(name, self.price, self.product))

class Mediator:

    def __init__(self): = "tertium quid"
        self.consumer = None
        self.producer = None

    def sale(self):
        """Stock purchase"""

    def shopping(self):

    def profit(self):
        print('Intermediary net income:{}'.format((self.consumer.price - self.producer.price )))

    def complete(self):

if __name__ == '__main__':
    consumer = Consumer('Mobile phone'3000)
    producer = Producer("Mobile phone"2500)
    mediator = Mediator()
    mediator.consumer = consumer
    mediator.producer = producer

# To producers purchase 3000 In price Mobile phone products
# Consumers Sale 2500 Price Mobile phone products
#Net income of intermediary: 500

Usage scenario: 1. There is a relatively complex reference relationship between objects in the system, resulting in the confusion of their dependency structure and the difficulty of reusing the object. 2. You want to encapsulate behaviors in multiple classes through an intermediate class, but you don't want to generate too many subclasses.

Note: it should not be used in case of confusion of duties.

Keywords: Python Mobile

Added by vweston on Wed, 04 Dec 2019 22:57:46 +0200