Introduction and use of Python intermediary mode

Table of contents


1. Introduction to Python intermediary mode

The Python Mediator pattern is a behavioral design pattern that allows multiple objects to communicate without having direct references to each other. In this pattern, a mediator object controls the communication between multiple objects, thereby reducing the coupling between objects.

Function:

  1. Transform complex relationships between objects into simple relationships between mediators and objects;
  2. Reduce the coupling of the system so that objects can change independently;
  3. Promote collaboration and communication between objects, improve system maintainability and scalability.

advantage:

  1. It can reduce the coupling between objects and reduce code duplication;
  2. Loose coupling between objects can be achieved, making system expansion and maintenance easier;
  3. It can improve the flexibility of the system and make the system easier to collaborate and communicate.

shortcoming:

  1. Mediator objects can become complex and difficult to maintain;
  2. The Mediator pattern can lead to reduced system performance because communication between objects needs to be passed through the Mediator object.

Application scenario:

  1. The interaction between objects is complex and difficult to maintain;
  2. The coupling degree between objects is relatively high, and it is difficult to achieve loose coupling of objects;
  3. Communication between objects needs to be coordinated and controlled through an intermediary.

How to use:

  1. Define the mediator interface: define the mediator class, which contains methods for coordinating and controlling communication between objects;
  2. Define an abstract object class: define an abstract object class, including methods that need to be coordinated and controlled, and a member variable that saves the intermediary object;
  3. Realize the specific object class: realize the method of the abstract object class, and call the method of the intermediary object in it to complete the communication between the objects;
  4. Build a mediator object: build a mediator object and save all abstract object class objects in it;
  5. Test code: Create an abstract object class and a mediator object in the client code, and then use the abstract object class object to call methods to complete the communication between objects.

Application in application development:

  1. GUI interface development: The controller object in the MVC pattern is an intermediary object, which is responsible for coordinating the communication between the view and the model;
  2. Chat room system: In the chat room system, the intermediary object is responsible for coordinating the communication between users;
  3. Game development: The AI ​​controller in the game is an intermediary object, which coordinates the communication between the various objects in the game.

2. Use of intermediary mode

working principle:

  1. When an object changes, it notifies the mediator object;
  2. After the intermediary object receives the notification, it will call the method of other objects to complete the communication between objects;
  3. When objects need to communicate, they will send requests to the mediator object, and then the mediator object will forward the request to other objects to complete the communication between objects.

Example: Implementing player functionality

An example to illustrate the Python intermediary pattern:

Suppose we want to develop a simple multimedia player, which has three buttons: play, stop, pause, and a text box to display the current state. Each button and text box is an object, and the three buttons need to communicate with each other. If each button communicated directly with every other button, the code would become very complex and difficult to maintain. At this time, the intermediary mode can be used to reduce the coupling between objects and improve the maintainability of the system.

working principle:

  1. Create a mediator class, containing methods for coordinating and controlling communication between objects;
  2. Create an abstract object class that contains the methods that need to be coordinated and controlled, and a member variable that holds the intermediary object;
  3. Create a concrete object class, implement the method of the abstract object class, and call the method of the intermediary object in it to complete the communication between objects;
  4. Create a mediator object and save all abstract object class objects in it;
  5. Create an abstract object class and a mediator object in the client code, and then use the abstract object class object to call methods to complete the communication between objects.

The following is a sample Python code implementation:

# 创建中介者类, 播放器
class Mediator():
    def __init__(self):
        self.play_button = None # 播放
        self.stop_button = None # 停止
        self.pause_button = None# 暂停
        self.text_box = None    # 文本框:显示当前状态

    def set_play_button(self, play_button):
        self.play_button = play_button

    def set_stop_button(self, stop_button):
        self.stop_button = stop_button

    def set_pause_button(self, pause_button):
        self.pause_button = pause_button

    def set_text_box(self, text_box):
        self.text_box = text_box

    def play(self):
        self.text_box.set_text("Playing...")
    def stop(self):
        self.text_box.set_text("Stoppped.")
    def pause(self):
        self.text_box.set_text("Paused.")

# 创建抽象对象类
class Buttton():
    def __init__(self, mediator):
        self.mediator = mediator

    def click(self):
        pass

class TextBox():
    def __init__(self, mediator):
        self.text = ""
        self.mediator = mediator

    def set_text(self, text):
        self.text = text
        print(self.text)

# 定义具体对象类
class PlayButton(Buttton):
    def click(self):
        self.mediator.play()
class StopButton(Buttton):
    def click(self):
        self.mediator.stop()
class PauseButton(Buttton):
    def click(self):
        self.mediator.pause()

# 创建对象
mediator = Mediator()

play_button = PlayButton(mediator)
stop_button = StopButton(mediator)
pause_button = PauseButton(mediator)
text_box = TextBox(mediator)

mediator.set_play_button(play_button)
mediator.set_stop_button(stop_button)
mediator.set_pause_button(pause_button)
mediator.set_text_box(text_box)

play_button.click()
pause_button.click()
stop_button.click()

operation result:

Playing...
Paused.
Stoppped.

In the above code, we created a mediator class Mediator, abstract object classes Button and TextBox, and concrete object classes PlayButton, StopButton and PauseButton. Among them, the abstract object classes Button and TextBox both contain a member variable mediator pointing to the mediator object, and the concrete object classes PlayButton, StopButton and PauseButton implement the click method of the abstract object class Button, and call the mediator object’s play, pause and stop method. In the mediator class Mediator, we define three methods play, stop and pause, and set the content of the text box in them.

In the test code, we create the button and textbox objects and set them into the mediator object. Then by calling the click method of the button object to simulate the behavior of the user clicking the button, thereby triggering the communication between the various objects. Finally, we can see that the correct status information is output on the text box, proving that the communication between the various objects has been successfully completed.

Instructions:

  1. Define a mediator class, containing methods for coordinating and controlling communication between objects;
  2. Define an abstract object class, including methods that need to be coordinated and controlled, and a member variable that holds the intermediary object;
  3. Realize the specific object class, realize the method of the abstract object class, and call the method of the intermediary object in it, and complete the communication between the objects;
  4. Create a mediator object and save all abstract object class objects in it;
  5. Create an abstract object class and a mediator object in the client code, and then use the abstract object class object to call methods to complete the communication between objects.

3. Appendix

Methods between different classes call each other by instantiating objects

class A():
    def method_a(self):
        print("method_a")

        b = B()
        b.method_b()

class B():
    def method_b(self):
        print("method_b")

a = A()
a.method_a() # 输出 method_a 和 method_b

Guess you like

Origin blog.csdn.net/songpeiying/article/details/131979913