• 设计模式:中介者模式(C#、JAVA、JavaScript、C++、Python、Go、PHP)


    上一篇《迭代器模式》                                                           下一篇《备忘录模式》

    简介:

    中介者模式,它是是一种行为设计模式,它允许将一组对象之间的交互封装到一个单独的类中,从而降低对象之间的耦合性,提高系统的灵活性和可维护性。

    中介者模式涉及到一个中介者对象和多个同事对象。中介者对象负责协调和管理同事对象之间的交互,而同事对象之间则通过中介者对象进行通信。这样,同事对象之间不再直接通信,而是通过中介者对象来进行间接交互。

    中介者模式适用于系统中存在一组密切相关的对象,并且这些对象之间的交互很复杂。通过引入中介者对象,可以将这些对象的交互逻辑集中到一个单独的类中,降低对象之间的耦合性,并提高系统的可维护性和可扩展性。

    实现中介者模式的关键步骤包括定义抽象中介者接口和具体中介者类,以及定义抽象同事类和具体同事类。中介者接口应该定义统一的接口用于各个同事角色之间的通信,具体中介者类则实现该接口并协调各个同事间的协作。同事类应该依赖中介者角色,并通过中介者进行通信。

    中介者模式的使用场景:
    1、系统中对象之间存在复杂的引用关系,产生的相互依赖关系结构混乱,难以理解。中介者模式可以将这些对象之间的交互逻辑集中到一个单独的类中,降低对象之间的耦合性,并提高系统的可维护性和可扩展性。
    2、一个对象由于引用了其他很多对象并且直接和这些对象通信,导致难以复用该对象。通过引入中介者对象,可以将该对象的依赖关系转移到中介者对象上,从而实现对象的松散耦合,提高对象的可复用性。
    3、需要在多个对象间定义一些公共行为,并且希望能够灵活地增加或修改这些行为。中介者模式可以通过定义抽象中介者接口和具体中介者类来封装一组对象之间的交互逻辑,并在需要时增加新的中介者类来实现行为的扩展。

    中介者模式的创建步骤:
    1、定义中介者接口:中介者接口应该定义统一的接口用于各个同事角色之间的通信。
    2、创建具体中介者类:具体中介者类实现中介者接口,并协调各个同事间的协作。
    3、定义同事接口:同事接口应该定义与中介者对象交互的接口。
    4、创建具体同事类:具体同事类实现同事接口,并定义与中介者对象交互的具体实现。
    5、创建同事对象:创建多个同事对象,每个对象都具有自己的行为和状态。
    6、创建中介者对象:创建中介者对象,并将各个同事对象作为参数传递给中介者对象。
    7、使用中介者对象:通过中介者对象调用各个同事对象的方法,实现对象之间的间接交互。

    中介者模式的优点,主要包括:
    1、降低对象之间的耦合性:通过引入中介者对象,可以将原本相互依赖的对象之间的关系转化为中介者和同事对象之间的交互,从而降低对象之间的耦合性,提高系统的灵活性和可维护性。
    2、提高系统的可维护性和可扩展性:中介者模式可以将一组对象的交互逻辑集中到一个单独的类中,使得系统的维护和扩展变得更加方便。当需要修改对象之间的交互逻辑时,只需要修改中介者对象即可,而不需要修改各个同事对象的代码。
    3、符合迪米特法则:中介者模式使得各个同事对象之间解耦,符合迪米特法则。同时,由于各个同事对象之间的交互都通过中介者对象来完成,也符合里氏替换原则。
    4、提高代码的可读性和可维护性:通过将复杂的交互逻辑集中到一个单独的类中,中介者模式使得代码更加清晰易懂,也方便后续的维护和扩展。

    中介者模式的缺点,主要包括:
    1、中介者对象可能会变得复杂且庞大:当系统中需要协调的对象越来越多时,中介者对象也可能会变得复杂且庞大,导致系统变得难以理解和维护。
    2、中介者对象可能会成为系统的瓶颈:由于所有对象之间的交互都需要通过中介者对象来完成,当系统中需要交互的对象非常多时,中介者对象可能会成为系统的瓶颈,影响系统的性能。
    3、中介者模式可能会导致系统的可扩展性降低:由于中介者对象负责协调各个对象之间的交互,当需要添加新的对象或新的交互逻辑时,可能需要对中介者对象进行修改,这会限制系统的可扩展性。
    4、中介者模式可能会导致代码的可读性和可维护性降低:由于中介者对象需要处理多个对象之间的交互逻辑,代码可能会变得复杂且难以理解,这会降低代码的可读性和可维护性。

    示例:

    一、C#中介者模式

    以下是一个示例,展示了如何在C#中实现中介者模式:

    1. using System;  
    2.   
    3. namespace MediatorPatternExample  
    4. {  
    5.     // 中介者接口  
    6.     public interface IMediator  
    7.     {  
    8.         void Register(Colleague colleague);  
    9.         void Unregister(Colleague colleague);  
    10.         void Notify(string message);  
    11.     }  
    12.   
    13.     // 中介者类  
    14.     public classMediator : IMediator  
    15.     {  
    16.         private List colleagues = new List();  
    17.   
    18.         public void Register(Colleague colleague)  
    19.         {  
    20.             colleagues.Add(colleague);  
    21.         }  
    22.   
    23.         public void Unregister(Colleague colleague)  
    24.         {  
    25.             colleagues.Remove(colleague);  
    26.         }  
    27.   
    28.         public void Notify(string message)  
    29.         {  
    30.             foreach (var colleague in colleagues)  
    31.             {  
    32.                 colleague.Receive(message);  
    33.             }  
    34.         }  
    35.     }  
    36.   
    37.     // 同事接口  
    38.     public interface IColleague  
    39.     {  
    40.         void Receive(string message);  
    41.     }  
    42.   
    43.     // 具体同事类A  
    44.     public class ColleagueA : IColleague  
    45.     {  
    46.         public void Receive(string message)  
    47.         {  
    48.             Console.WriteLine("Colleague A received message: " + message);  
    49.         }  
    50.     }  
    51.   
    52.     // 具体同事类B  
    53.     public class ColleagueB : IColleague  
    54.     {  
    55.         public void Receive(string message)  
    56.         {  
    57.             Console.WriteLine("Colleague B received message: " + message);  
    58.         }  
    59.     }  
    60.   
    61.     // 客户端代码  
    62.     class Program  
    63.     {  
    64.         static void Main(string[] args)  
    65.         {  
    66.             IMediator mediator = newMediator();  
    67.             IColleague colleagueA = new ColleagueA();  
    68.             IColleague colleagueB = new ColleagueB();  
    69.             mediator.Register(colleagueA); // 注册同事对象A和B到中介者对象中  
    70.             mediator.Register(colleagueB); // 注册同事对象A和B到中介者对象中,也可以在程序运行过程中随时取消注册或添加新的同事对象,非常灵活方便。        
    71.         }
    72.     }
    73. }

    二、java中介者模式

    中介者模式通常通过以下方式实现:

    1. // 中介者接口  
    2. interface Mediator {  
    3.     void register(Colleague colleague);  
    4.     void unregister(Colleague colleague);  
    5.     void notify(String message);  
    6. }  
    7.   
    8. // 具体中介者类  
    9. class ConcreteMediator implements Mediator {  
    10.     private List colleagues = new ArrayList<>();  
    11.   
    12.     @Override  
    13.     public void register(Colleague colleague) {  
    14.         colleagues.add(colleague);  
    15.     }  
    16.   
    17.     @Override  
    18.     public void unregister(Colleague colleague) {  
    19.         colleagues.remove(colleague);  
    20.     }  
    21.   
    22.     @Override  
    23.     public void notify(String message) {  
    24.         for (Colleague colleague : colleagues) {  
    25.             colleague.receive(message);  
    26.         }  
    27.     }  
    28. }  
    29.   
    30. // 同事接口  
    31. interface Colleague {  
    32.     void receive(String message);  
    33. }  
    34.   
    35. // 具体同事类A  
    36. class ColleagueA implements Colleague {  
    37.     @Override  
    38.     public void receive(String message) {  
    39.         System.out.println("Colleague A received message: " + message);  
    40.     }  
    41. }  
    42.   
    43. // 具体同事类B  
    44. class ColleagueB implements Colleague {  
    45.     @Override  
    46.     public void receive(String message) {  
    47.         System.out.println("Colleague B received message: " + message);  
    48.     }  
    49. }  
    50.   
    51. // 客户端代码  
    52. public class Client {  
    53.     public static void main(String[] args) {  
    54.         Mediator mediator = new ConcreteMediator();  
    55.         Colleague colleagueA = new ColleagueA();  
    56.         Colleague colleagueB = new ColleagueB();  
    57.         mediator.register(colleagueA); // 注册同事对象A和B到中介者对象中  
    58.         mediator.register(colleagueB); // 注册同事对象A和B到中介者对象中,也可以在程序运行过程中随时取消注册或添加新的同事对象,非常灵活方便。     
    59.         
    60.     }
    61. }

    三、javascript中介者模式

    在JavaScript中,中介者实现方式如下:

    1. // 定义中介者接口  
    2. var Mediator = {  
    3.   register: function(colleague),  
    4.   unregister: function(colleague),  
    5.   notify: function(message)  
    6. };  
    7.   
    8. // 具体中介者类  
    9. var ConcreteMediator = Object.create(Mediator);  
    10.   
    11. ConcreteMediator.register = function(colleague) {  
    12.   this.colleagues.push(colleague);  
    13. };  
    14.   
    15. ConcreteMediator.unregister = function(colleague) {  
    16.   this.colleagues = this.colleagues.filter(function(obj) {  
    17.     return obj !== colleague;  
    18.   });  
    19. };  
    20.   
    21. ConcreteMediator.notify = function(message) {  
    22.   this.colleagues.forEach(function(colleague) {  
    23.     colleague.receive(message);  
    24.   });  
    25. };  
    26.   
    27. // 定义同事接口  
    28. var Colleague = {  
    29.   receive: function(message)  
    30. };  
    31.   
    32. // 具体同事类A  
    33. var ColleagueA = Object.create(Colleague);  
    34. ColleagueA.receive = function(message) {  
    35.   console.log("Colleague A received message: " + message);  
    36. };  
    37.   
    38. // 具体同事类B  
    39. var ColleagueB = Object.create(Colleague);  
    40. ColleagueB.receive = function(message) {  
    41.   console.log("Colleague B received message: " + message);  
    42. };  
    43.   
    44. // 客户端代码  
    45. var mediator = new ConcreteMediator();  
    46. var colleagueA = new ColleagueA();  
    47. var colleagueB = new ColleagueB();  
    48. mediator.register(colleagueA); // 注册同事对象A和B到中介者对象中  
    49. mediator.register(colleagueB);    

    四、C++中介者模式

    以下是在C++中实现中介者模式:

    1. #include  
    2. #include  
    3.   
    4. // 中介者接口  
    5. class Mediator {  
    6. public:  
    7.     virtual void registerColleague(std::string name, Mediator* colleague) = 0;  
    8.     virtual void unregisterColleague(std::string name) = 0;  
    9.     virtual void notify(std::string message) = 0;  
    10. };  
    11.   
    12. // 具体中介者类  
    13. class ConcreteMediator : public Mediator {  
    14. public:  
    15.     ConcreteMediator() {  
    16.         colleagues.reserve(3); // 预分配内存空间,提高性能  
    17.     }  
    18.   
    19.     void registerColleague(std::string name, Mediator* colleague) override {  
    20.         colleagues[name] = colleague; // 将同事对象存储在字典中,以名称作为键  
    21.     }  
    22.   
    23.     void unregisterColleague(std::string name) override {  
    24.         colleagues.erase(name); // 从字典中删除同事对象  
    25.     }  
    26.   
    27.     void notify(std::string message) override {  
    28.         for (auto& [name, colleague] : colleagues) {  
    29.             colleague->receive(message); // 遍历字典,通知所有注册的同事对象某个事件发生了  
    30.         }  
    31.     }  
    32.   
    33. private:  
    34.     std::unordered_map colleagues; // 将同事对象存储在字典中,以名称作为键,便于查找和删除  
    35. };  
    36.   
    37. // 同事接口  
    38. class Colleague {  
    39. public:  
    40.     virtual void receive(std::string message) = 0;  
    41. };  
    42.   
    43. // 具体同事类A  
    44. class ColleagueA : public Colleague {  
    45. public:  
    46.     void receive(std::string message) override {  
    47.         std::cout << "Colleague A received message: " << message << std::endl;  
    48.     }  
    49. };  
    50.   
    51. // 具体同事类B  
    52. class ColleagueB : public Colleague {  
    53. public:  
    54.     void receive(std::string message) override {  
    55.         std::cout << "Colleague B received message: " << message << std::endl;  
    56.     }  
    57. };  
    58.   
    59. int main() {  
    60.     ConcreteMediator mediator; // 创建具体中介者对象  
    61.     ColleagueA colleagueA; // 创建同事对象A和B,并将它们注册到中介者对象中。
    62.     ColleagueB colleagueB;
    63.     mediator.registerColleague("A", colleagueA);
    64.     mediator.registerColleague("B", colleagueB);
    65.     
    66.     mediator.notify("test colleagueA receive");//
    67. }

    五、python中介者模式

    以下是在python中实现中介者模式:

    1. from abc import ABC, abstractmethod  
    2.   
    3. # 中介者接口  
    4. class Mediator(ABC):  
    5.     @abstractmethod  
    6.     def register(self, colleague):  
    7.         pass  
    8.   
    9.     @abstractmethod  
    10.     def unregister(self, colleague):  
    11.         pass  
    12.   
    13.     @abstractmethod  
    14.     def notify(self, message):  
    15.         pass  
    16.   
    17. # 具体中介者类  
    18. class ConcreteMediator(Mediator):  
    19.     def __init__(self):  
    20.         self.colleagues = []  
    21.   
    22.     def register(self, colleague):  
    23.         self.colleagues.append(colleague)  
    24.   
    25.     def unregister(self, colleague):  
    26.         self.colleagues = [c for c in self.colleagues if c != colleague]  
    27.   
    28.     def notify(self, message):  
    29.         for colleague in self.colleagues:  
    30.             colleague.receive(message)  
    31.   
    32. # 同事接口  
    33. class Colleague(ABC):  
    34.     @abstractmethod  
    35.     def receive(self, message):  
    36.         pass  
    37.   
    38. # 具体同事类A和B,并将它们注册到中介者对象中。同时,当需要通知所有同事某个事件发生时,中介者对象可以调用 `notify()` 方法。  
    39. class ColleagueA(Colleague):  
    40.     def receive(self, message):  
    41.         print(f"Colleague A received message: {message}")  
    42.   
    43. class ColleagueB(Colleague):  
    44.     def receive(self, message):  
    45.         print(f"Colleague B received message: {message}")  
    46.   
    47. # 创建具体中介者对象和同事对象A和B,并将它们注册到中介者对象中。同时,当需要通知所有同事某个事件发生时,中介者对象可以调用 `notify()` 方法。  
    48. mediator = ConcreteMediator()  
    49. colleague_a = ColleagueA()  
    50. colleague_b = ColleagueB()  
    51. mediator.register(colleague_a)  
    52. mediator.register(colleague_b)  
    53. mediator.notify("Hello World!")

    六、go中介者模式

    以下是一个示例,展示了如何在go中实现中介者模式:

    1. package main  
    2.   
    3. import "fmt"  
    4.   
    5. // 同事接口  
    6. type Colleague interface {  
    7.  Receive(message string)  
    8. }  
    9.   
    10. // 中介者接口  
    11. type Mediator interface {  
    12.  Register(colleague Colleague)  
    13.  Unregister(colleague Colleague)  
    14.  Notify(message string)  
    15. }  
    16.   
    17. // 具体同事类A  
    18. type ColleagueA struct {  
    19.  mediator Mediator  
    20. }  
    21.   
    22. func (c *ColleagueA) Receive(message string) {  
    23.  fmt.Println("Colleague A received message:", message)  
    24.  c.mediator.Notify("Colleague A received message: " + message)  
    25. }  
    26.   
    27. // 具体同事类B  
    28. type ColleagueB struct {  
    29.  mediator Mediator  
    30. }  
    31.   
    32. func (c *ColleagueB) Receive(message string) {  
    33.  fmt.Println("Colleague B received message:", message)  
    34.  c.mediator.Notify("Colleague B received message: " + message)  
    35. }  
    36.   
    37. // 具体中介者类  
    38. type ConcreteMediator struct {  
    39.  colleagues []Colleague  
    40. }  
    41.   
    42. func (m *ConcreteMediator) Register(colleague Colleague) {  
    43.  m.colleagues = append(m.colleagues, colleague)  
    44. }  
    45.   
    46. func (m *ConcreteMediator) Unregister(colleague Colleague) {  
    47.  for i, c := range m.colleagues {  
    48.  if c == colleague {  
    49.  m.colleagues = append(m.colleagues[:i], m.colleagues[i+1:]...)  
    50.  break  
    51.  }  
    52.  }  
    53. }  
    54.   
    55. func (m *ConcreteMediator) Notify(message string) {  
    56.  for _, colleague := range m.colleagues {  
    57.  colleague.Receive(message)  
    58.  }  
    59. }  
    60.   
    61. func main() {  
    62.  mediator := &ConcreteMediator{}  
    63.  colleagueA := &ColleagueA{mediator}  
    64.  colleagueB := &ColleagueB{mediator}  
    65.  mediator.Register(colleagueA)  
    66.  mediator.Register(colleagueB)  
    67.  mediator.Notify("Hello World!"
    68. }    

    注意:在实现中介者模式时,需要谨慎处理同事对象之间的通信,避免产生无限循环或其他不良后果。

    七、PHP中介者模式

    以下是一个示例,展示了如何在PHP中实现中介者模式:

    1.  
    2.   
    3. // 定义中介者接口  
    4. interface Mediator {  
    5.     public function register($colleague);  
    6.     public function unregister($colleague);  
    7.     public function notify($message);  
    8. }  
    9.   
    10. // 具体中介者类  
    11. class ConcreteMediator implements Mediator {  
    12.     private $colleagues;  
    13.       
    14.     public function __construct() {  
    15.         $this->colleagues = [];  
    16.     }  
    17.       
    18.     public function register($colleague) {  
    19.         $this->colleagues[] = $colleague;  
    20.     }  
    21.       
    22.     public function unregister($colleague) {  
    23.         $index = array_search($colleague, $this->colleagues);  
    24.         if ($index !== false) {  
    25.             unset($this->colleagues[$index]);  
    26.         }  
    27.     }  
    28.       
    29.     public function notify($message) {  
    30.         foreach ($this->colleagues as $colleague) {  
    31.             $colleague->receive($message);  
    32.         }  
    33.     }  
    34. }  
    35.   
    36. // 定义同事接口  
    37. interface Colleague {  
    38.     public function receive($message);  
    39. }  
    40.   
    41. // 具体同事类A  
    42. class ColleagueA implements Colleague {  
    43.     private $mediator;  
    44.       
    45.     public function __construct(Mediator $mediator) {  
    46.         $this->mediator = $mediator;  
    47.     }  
    48.       
    49.     public function receive($message) {  
    50.         echo "Colleague A received message: " . $message . "\n";  
    51.         $this->mediator->notify("Colleague A received message: " . $message);  
    52.     }  
    53. }  
    54.   
    55. // 具体同事类B  
    56. class ColleagueB implements Colleague {  
    57.     private $mediator;  
    58.       
    59.     public function __construct(Mediator $mediator) {  
    60.         $this->mediator = $mediator;  
    61.     }  
    62.       
    63.     public function receive($message) {  
    64.         echo "Colleague B received message: " . $message . "\n";  
    65.         $this->mediator->notify("Colleague B received message: " . $message);  
    66.     }  
    67. }  
    68.   
    69. // 使用示例  
    70. $mediator = new ConcreteMediator();  
    71. $colleagueA = new ColleagueA($mediator);  
    72. $colleagueB = new ColleagueB($mediator);  
    73. $mediator->register($colleagueA);  
    74. $mediator->register($colleagueB);  
    75. $mediator->notify("Hello World!");
    76.                                   
    77. ?>


    《完结》
    上一篇《迭代器模式》                                                                下一篇《备忘录模式》

  • 相关阅读:
    Shell--常用小工具(sort、uniq、tr、cut)
    docker使用php较老版本出现pecl无法安装扩展问题
    Python入门教程 | Python 模块和包
    linux定时任务(crontab)
    俄罗斯方块
    容器化 | 使用 Alpine 构建 Redis 镜像
    ZYNQ 程序编译
    java毕业设计大学生赞助系统mybatis+源码+调试部署+系统+数据库+lw
    java毕业设计网上购物商城系统研发mybatis+源码+调试部署+系统+数据库+lw
    Win11系统提示backgroundtaskhost.exe系统错误解决方法
  • 原文地址:https://blog.csdn.net/yetyrain/article/details/134021471