程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python design pattern - behavioral pattern - mediator pattern

編輯:Python

Catalog

List of articles

  • Catalog
  • Intermediary model
  • Application scenarios
  • Code example

Intermediary model

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 .

Application scenarios

  • There are complex reference relationships between objects in the system , As a result, the dependency structure between them is chaotic and it is difficult to reuse the object .
  • I want to encapsulate behaviors in multiple classes through an intermediate class , And don't want to generate too many subclasses .

Code example

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()

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved