设计模式系列—中介者模式

开发 前端
本篇和大家一起来学习中介者模式相关内容。

模式定义

定义一个中介对象来封装一系列对象之间的交互,使原有对象之间的耦合松散,且可以独立地改变它们之间的交互。中介者模式又叫调停模式,它是迪米特法则的典型应用。

 

  • 迪米特法则(Law of Demeter,LoD)又叫作最少知识原则(Least Knowledge Principle,LKP),产生于 1987 年美国东北大学(Northeastern University)的一个名为迪米特(Demeter)的研究项目,由伊恩·荷兰(Ian Holland)提出,被 UML 创始者之一的布奇(Booch)普及,后来又因为在经典著作《程序员修炼之道》(The Pragmatic Programmer)提及而广为人知。
  • 迪米特法则的定义是:只与你的直接朋友交谈,不跟“陌生人”说话(Talk only to your immediate friends and not to strangers)。其含义是:如果两个软件实体无须直接通信,那么就不应当发生直接的相互调用,可以通过第三方转发该调用。其目的是降低类之间的耦合度,提高模块的相对独立性。
  • 迪米特法则中的“朋友”是指:当前对象本身、当前对象的成员对象、当前对象所创建的对象、当前对象的方法参数等,这些对象同当前对象存在关联、聚合或组合关系,可以直接访问这些对象的方法。

模板实现如下:

  1. package com.niuh.designpattern.mediator.v1; 
  2.  
  3. import java.util.ArrayList; 
  4. import java.util.List; 
  5.  
  6. /** 
  7.  * <p> 
  8.  * 中介者模式 
  9.  * </p> 
  10.  */ 
  11. public class MediatorPattern { 
  12.  
  13.     public static void main(String[] args) { 
  14.         Mediator md = new ConcreteMediator(); 
  15.         Colleague c1, c2; 
  16.         c1 = new ConcreteColleague1(); 
  17.         c2 = new ConcreteColleague2(); 
  18.         md.register(c1); 
  19.         md.register(c2); 
  20.         c1.send(); 
  21.         System.out.println("=============="); 
  22.         c2.send(); 
  23.     } 
  24.  
  25. //抽象中介者 
  26. abstract class Mediator { 
  27.     public abstract void register(Colleague colleague); 
  28.  
  29.     public abstract void relay(Colleague cl); //转发 
  30.  
  31. //具体中介者 
  32. class ConcreteMediator extends Mediator { 
  33.     private List<Colleague> colleagues = new ArrayList<Colleague>(); 
  34.  
  35.     public void register(Colleague colleague) { 
  36.         if (!colleagues.contains(colleague)) { 
  37.             colleagues.add(colleague); 
  38.             colleague.setMedium(this); 
  39.         } 
  40.     } 
  41.  
  42.     public void relay(Colleague cl) { 
  43.         for (Colleague ob : colleagues) { 
  44.             if (!ob.equals(cl)) { 
  45.                 ((Colleague) ob).receive(); 
  46.             } 
  47.         } 
  48.     } 
  49.  
  50. //抽象同事类 
  51. abstract class Colleague { 
  52.     protected Mediator mediator; 
  53.  
  54.     public void setMedium(Mediator mediator) { 
  55.         this.mediator = mediator; 
  56.     } 
  57.  
  58.     public abstract void receive(); 
  59.  
  60.     public abstract void send(); 
  61.  
  62. //具体同事类 
  63. class ConcreteColleague1 extends Colleague { 
  64.     public void receive() { 
  65.         System.out.println("具体同事类1收到请求。"); 
  66.     } 
  67.  
  68.     public void send() { 
  69.         System.out.println("具体同事类1发出请求。"); 
  70.         mediator.relay(this); //请中介者转发 
  71.     } 
  72.  
  73. //具体同事类 
  74. class ConcreteColleague2 extends Colleague { 
  75.     public void receive() { 
  76.         System.out.println("具体同事类2收到请求。"); 
  77.     } 
  78.  
  79.     public void send() { 
  80.         System.out.println("具体同事类2发出请求。"); 
  81.         mediator.relay(this); //请中介者转发 
  82.     } 

结果实现如下:

  • 具体同事类1发出请求。
  • 具体同事类2收到请求。
  • 具体同事类2发出请求。
  • 具体同事类1收到请求。

解决的问题

对象与对象之间存在大量的关联关系,这样势必会导致系统的结构变得很复杂,同时若一个对象发生改变,我们也需要跟踪与之相关联的对象,同时做出相应的处理。

模式组成

 

中介者模式实现的关键是找出“中介者”。

实例说明

实例概况

用中介者模式编写一个“北京房地产交流平台”程序。

 

分析:北京房地产交流平台是“房地产中介公司”提供给“卖方客户”与“买方客户”进行信息交流的平台,比较适合用中介者模式来实现。

使用步骤

 

步骤1:定义一个中介公司(Medium)接口,它是抽象中介者,它包含了客户注册方法 register(Customer member) 和信息转发方法 relay(String from,String ad);

  1. interface Medium { 
  2.     //客户注册 
  3.     void register(Customer member); 
  4.  
  5.     //转发 
  6.     void relay(String from, String ad); 

步骤2:定义一个北京房地产中介(EstateMedium)公司,它是具体中介者类,它包含了保存客户信息的 List 对象,并实现了中介公司中的抽象方法。

  1. //具体中介者:房地产中介 
  2. class EstateMedium implements Medium { 
  3.     private List<Customer> members = new ArrayList<Customer>(); 
  4.  
  5.     public void register(Customer member) { 
  6.         if (!members.contains(member)) { 
  7.             members.add(member); 
  8.             member.setMedium(this); 
  9.         } 
  10.     } 
  11.  
  12.     public void relay(String from, String ad) { 
  13.         for (Customer ob : members) { 
  14.             String name = ob.getName(); 
  15.             if (!name.equals(from)) { 
  16.                 ((Customer) ob).receive(from, ad); 
  17.             } 
  18.         } 
  19.     } 

步骤3:定义一个客户(Qistomer)类,它是抽象同事类,其中包含了中介者的对象,和发送信息的 send(String ad) 方法与接收信息的 receive(String from,Stringad) 方法的接口,由于本程序是窗体程序,所以本类继承 JPmme 类,并实现动作事件的处理方法 actionPerformed(ActionEvent e)。

  1. //抽象同事类:客户 
  2. abstract class Customer extends JFrame implements ActionListener { 
  3.     private static final long serialVersionUID = -7219939540794786080L; 
  4.     protected Medium medium; 
  5.     protected String name
  6.     JTextField SentText; 
  7.     JTextArea ReceiveArea; 
  8.  
  9.     public Customer(String name) { 
  10.         super(name); 
  11.         this.name = name
  12.     } 
  13.  
  14.     void ClientWindow(int x, int y) { 
  15.         Container cp; 
  16.         JScrollPane sp; 
  17.         JPanel p1, p2; 
  18.         cp = this.getContentPane(); 
  19.         SentText = new JTextField(18); 
  20.         ReceiveArea = new JTextArea(10, 18); 
  21.         ReceiveArea.setEditable(false); 
  22.         p1 = new JPanel(); 
  23.         p1.setBorder(BorderFactory.createTitledBorder("接收内容:")); 
  24.         p1.add(ReceiveArea); 
  25.         sp = new JScrollPane(p1); 
  26.         cp.add(sp, BorderLayout.NORTH); 
  27.         p2 = new JPanel(); 
  28.         p2.setBorder(BorderFactory.createTitledBorder("发送内容:")); 
  29.         p2.add(SentText); 
  30.         cp.add(p2, BorderLayout.SOUTH); 
  31.         SentText.addActionListener(this); 
  32.         this.setLocation(x, y); 
  33.         this.setSize(250, 330); 
  34.         this.setResizable(false); //窗口大小不可调整 
  35.         this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
  36.         this.setVisible(true); 
  37.     } 
  38.  
  39.     public void actionPerformed(ActionEvent e) { 
  40.         String tempInfo = SentText.getText().trim(); 
  41.         SentText.setText(""); 
  42.         this.send(tempInfo); 
  43.     } 
  44.  
  45.     public String getName() { 
  46.         return name
  47.     } 
  48.  
  49.     public void setMedium(Medium medium) { 
  50.         this.medium = medium; 
  51.     } 
  52.  
  53.     public abstract void send(String ad); 
  54.  
  55.     public abstract void receive(String from, String ad); 

步骤4:定义卖方(Seller)类和买方(Buyer)类,它们是具体同事类,是客户(Customer)类的子类,它们实现了父类中的抽象方法,通过中介者类进行信息交流。

  1. //具体同事类:卖方 
  2. class Seller extends Customer { 
  3.     private static final long serialVersionUID = -1443076716629516027L; 
  4.  
  5.     public Seller(String name) { 
  6.         super(name); 
  7.         ClientWindow(50, 100); 
  8.     } 
  9.  
  10.     public void send(String ad) { 
  11.         ReceiveArea.append("我(卖方)说: " + ad + "\n"); 
  12.         //使滚动条滚动到最底端 
  13.         ReceiveArea.setCaretPosition(ReceiveArea.getText().length()); 
  14.         medium.relay(name, ad); 
  15.     } 
  16.  
  17.     public void receive(String from, String ad) { 
  18.         ReceiveArea.append(from + "说: " + ad + "\n"); 
  19.         //使滚动条滚动到最底端 
  20.         ReceiveArea.setCaretPosition(ReceiveArea.getText().length()); 
  21.     } 
  22.  
  23. //具体同事类:买方 
  24. class Buyer extends Customer { 
  25.     private static final long serialVersionUID = -474879276076308825L; 
  26.  
  27.     public Buyer(String name) { 
  28.         super(name); 
  29.         ClientWindow(350, 100); 
  30.     } 
  31.  
  32.     public void send(String ad) { 
  33.         ReceiveArea.append("我(买方)说: " + ad + "\n"); 
  34.         //使滚动条滚动到最底端 
  35.         ReceiveArea.setCaretPosition(ReceiveArea.getText().length()); 
  36.         medium.relay(name, ad); 
  37.     } 
  38.  
  39.     public void receive(String from, String ad) { 
  40.         ReceiveArea.append(from + "说: " + ad + "\n"); 
  41.         //使滚动条滚动到最底端 
  42.         ReceiveArea.setCaretPosition(ReceiveArea.getText().length()); 
  43.     } 

输出结果

优点

  1. 降低了对象之间的耦合性,使得对象易于独立地被复用。
  2. 将对象间的一对多关联转变为一对一的关联,提高系统的灵活性,使得系统易于维护和扩展。

缺点

当同事类太多时,中介者的职责将很大,它会变得复杂而庞大,以至于系统难以维护。

应用场景

  • 当对象之间存在复杂的网状结构关系而导致依赖关系混乱且难以复用时。
  • 当想创建一个运行于多个类之间的对象,又不想生成新的子类时。

模式的扩展

在实际开发中,通常采用以下两种方法来简化中介者模式,使开发变得更简单。

 

  1. 不定义中介者接口,把具体中介者对象实现成为单例。
  2. 同事对象不持有中介者,而是在需要的时候直接获取中介者对象并调用。

程序代码如下:

  1. package com.niuh.designpattern.mediator.v3; 
  2.  
  3. import java.util.ArrayList; 
  4. import java.util.List; 
  5.  
  6. /** 
  7.  * <p> 
  8.  * 简化中介者模式 
  9.  * </p> 
  10.  */ 
  11. public class SimpleMediatorPattern { 
  12.     public static void main(String[] args) { 
  13.         SimpleColleague c1, c2; 
  14.         c1 = new SimpleConcreteColleague1(); 
  15.         c2 = new SimpleConcreteColleague2(); 
  16.         c1.send(); 
  17.         System.out.println("=============="); 
  18.         c2.send(); 
  19.     } 
  20.  
  21. //简单单例中介者 
  22. class SimpleMediator { 
  23.     private static SimpleMediator smd = new SimpleMediator(); 
  24.     private List<SimpleColleague> colleagues = new ArrayList<SimpleColleague>(); 
  25.  
  26.     private SimpleMediator() { 
  27.     } 
  28.  
  29.     public static SimpleMediator getMedium() { 
  30.         return (smd); 
  31.     } 
  32.  
  33.     public void register(SimpleColleague colleague) { 
  34.         if (!colleagues.contains(colleague)) { 
  35.             colleagues.add(colleague); 
  36.         } 
  37.     } 
  38.  
  39.     public void relay(SimpleColleague scl) { 
  40.         for (SimpleColleague ob : colleagues) { 
  41.             if (!ob.equals(scl)) { 
  42.                 ((SimpleColleague) ob).receive(); 
  43.             } 
  44.         } 
  45.     } 
  46.  
  47. //抽象同事类 
  48. interface SimpleColleague { 
  49.     void receive(); 
  50.  
  51.     void send(); 
  52.  
  53. //具体同事类 
  54. class SimpleConcreteColleague1 implements SimpleColleague { 
  55.     SimpleConcreteColleague1() { 
  56.         SimpleMediator smd = SimpleMediator.getMedium(); 
  57.         smd.register(this); 
  58.     } 
  59.  
  60.     public void receive() { 
  61.         System.out.println("具体同事类1:收到请求。"); 
  62.     } 
  63.  
  64.     public void send() { 
  65.         SimpleMediator smd = SimpleMediator.getMedium(); 
  66.         System.out.println("具体同事类1:发出请求..."); 
  67.         smd.relay(this); //请中介者转发 
  68.     } 
  69.  
  70. //具体同事类 
  71. class SimpleConcreteColleague2 implements SimpleColleague { 
  72.     SimpleConcreteColleague2() { 
  73.         SimpleMediator smd = SimpleMediator.getMedium(); 
  74.         smd.register(this); 
  75.     } 
  76.  
  77.     public void receive() { 
  78.         System.out.println("具体同事类2:收到请求。"); 
  79.     } 
  80.  
  81.     public void send() { 
  82.         SimpleMediator smd = SimpleMediator.getMedium(); 
  83.         System.out.println("具体同事类2:发出请求..."); 
  84.         smd.relay(this); //请中介者转发 
  85.     } 

输出结果如下:

  • 具体同事类1:发出请求...
  • 具体同事类2:收到请求。
  • 具体同事类2:发出请求...
  • 具体同事类1:收到请求。

 

源码中的应用

  1. java.util.Timer 
  2. java.util.concurrent.Executer#execute() 
  3. java.util.concurrent.ExecuterService#submit() 
  4. java.lang.reflect.Method#invoke() 

PS:以上代码提交在 Github :

https://github.com/Niuh-Study/niuh-designpatterns.git

 

责任编辑:姜华 来源: 今日头条
相关推荐

2023-05-26 08:41:23

模式Go设计模式

2021-07-20 08:52:20

命令模式中介者模式设计模式

2021-10-26 00:21:19

设计模式建造者

2020-10-20 13:33:00

建造者模式

2020-10-26 08:45:39

观察者模式

2021-01-21 05:34:14

设计模式建造者

2013-11-26 17:09:57

Android设计模式

2021-07-08 11:28:43

观察者模式设计

2023-10-07 00:17:06

AirDrop中介者模式

2022-01-29 22:12:35

前端模式观察者

2022-01-12 13:33:25

工厂模式设计

2020-10-23 09:40:26

设计模式

2020-11-03 13:05:18

命令模式

2020-11-04 08:54:54

状态模式

2021-03-02 08:50:31

设计单例模式

2021-09-29 13:53:17

抽象工厂模式

2022-01-14 09:22:22

设计模式桥接

2020-10-21 14:29:15

原型模式

2021-06-09 08:53:34

设计模式策略模式工厂模式

2020-10-19 09:28:00

抽象工厂模式
点赞
收藏

51CTO技术栈公众号