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):
        self.name = "Consumer"
        self.product = product
        self.price = price

    def shopping(self, name):
        """Shopping"""
        print("towards{} purchase {}In 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{} Sale {}Price {}product".format(name, self.price, self.product))


class Mediator:
    """Intermediaries"""

    def __init__(self):
        self.name = "tertium quid"
        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):
        """profit"""
        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()

# 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