中介者模式詳解


在現實生活中,常常會出現好多對象之間存在復雜的交互關系,這種交互關系常常是“網狀結構”,它要求每個對象都必須知道它需要交互的對象。例如,每個人必須記住他(她)所有朋友的電話;而且,朋友中如果有人的電話修改了,他(她)必須告訴其他所有的朋友修改,這叫作“牽一發而動全身”,非常復雜。

如果把這種“網狀結構”改為“星形結構”的話,將大大降低它們之間的“耦合性”,這時只要找一個“中介者”就可以了。如前面所說的“每個人必須記住所有朋友電話”的問題,只要在網上建立一個每個朋友都可以訪問的“通信錄”就解決了。這樣的例子還有很多,例如,你剛剛參力口工作想租房,可以找“房屋中介”;或者,自己剛剛到一個陌生城市找工作,可以找“人才交流中心”幫忙。

在軟件的開發過程中,這樣的例子也很多,例如,在 MVC 框架中,控制器(C)就是模型(M)和視圖(V)的中介者;還有大家常用的 QQ 聊天程序的“中介者”是 QQ 服務器。所有這些,都可以采用“中介者模式”來實現,它將大大降低對象之間的耦合性,提高系統的靈活性。
模式的定義與特點中介者(Mediator)模式的定義:定義一個中介對象來封裝一系列對象之間的交互,使原有對象之間的耦合松散,且可以獨立地改變它們之間的交互。中介者模式又叫調停模式,它是迪米特法則的典型應用。

中介者模式是一種對象行為型模式,其主要優點如下。

  • 降低了對象之間的耦合性,使得對象易於獨立地被復用。
  • 將對象間的一對多關聯轉變為一對一的關聯,提高系統的靈活性,使得系統易於維護和擴展。


其主要缺點是:當同事類太多時,中介者的職責將很大,它會變得復雜而龐大,以至於系統難以維護。
模式的結構與實現中介者模式實現的關鍵是找出“中介者”,下面對它的結構和實現進行分析。
1. 模式的結構中介者模式包含以下主要角色。

  • 抽象中介者(Mediator)角色:它是中介者的接口,提供了同事對象注冊與轉發同事對象信息的抽象方法。
  • 具體中介者(ConcreteMediator)角色:實現中介者接口,定義一個 List 來管理同事對象,協調各個同事角色之間的交互關系,因此它依賴於同事角色。
  • 抽象同事類(Colleague)角色:定義同事類的接口,保存中介者對象,提供同事對象交互的抽象方法,實現所有相互影響的同事類的公共功能。
  • 具體同事類(Concrete Colleague)角色:是抽象同事類的實現者,當需要與其他同事對象交互時,由中介者對象負責后續的交互。


中介者模式的結構圖如圖 1 所示。


圖1 中介者模式的結構圖


2. 模式的實現中介者模式的實現代碼如下:

  • package mediator;
  • import java.util.*;
  • public class MediatorPattern
  • {
  •     public static void main(String[] args)
  •     {
  •         Mediator md=new ConcreteMediator();
  •         Colleague c1,c2;
  •         c1=new ConcreteColleague1();
  •         c2=new ConcreteColleague2();
  •         md.register(c1);
  •         md.register(c2);
  •         c1.send();
  •         System.out.println("-------------");
  •         c2.send();
  •     }
  • }
  • //抽象中介者
  • abstract class Mediator
  • {
  •     public abstract void register(Colleague colleague);
  •     public abstract void relay(Colleague cl); //轉發
  • }
  • //具體中介者
  • class ConcreteMediator extends Mediator
  • {
  •     private List<Colleague> colleagues=new ArrayList<Colleague>();
  •     public void register(Colleague colleague)
  •     {
  •         if(!colleagues.contains(colleague))
  •         {
  •             colleagues.add(colleague);
  •             colleague.setMedium(this);
  •         }
  •     }
  •     public void relay(Colleague cl)
  •     {
  •         for(Colleague ob:colleagues)
  •         {
  •             if(!ob.equals(cl))
  •             {
  •                 ((Colleague)ob).receive();
  •             }
  •         }
  •     }
  • }
  • //抽象同事類
  • abstract class Colleague
  • {
  •     protected Mediator mediator;
  •     public void setMedium(Mediator mediator)
  •     {
  •         this.mediator=mediator;
  •     }
  •     public abstract void receive();
  •     public abstract void send();
  • }
  • //具體同事類
  • class ConcreteColleague1 extends Colleague
  • {
  •     public void receive()
  •     {
  •         System.out.println("具體同事類1收到請求。");
  •     }
  •     public void send()
  •     {
  •         System.out.println("具體同事類1發出請求。");
  •         mediator.relay(this); //請中介者轉發
  •     }
  • }
  • //具體同事類
  • class ConcreteColleague2 extends Colleague
  • {
  •     public void receive()
  •     {
  •         System.out.println("具體同事類2收到請求。");
  •     }
  •     public void send()
  •     {
  •         System.out.println("具體同事類2發出請求。");
  •         mediator.relay(this); //請中介者轉發
  •     }
  • }




程序的運行結果如下:具體同事類1發出請求。具體同事類2收到請求。-------------具體同事類2發出請求。具體同事類1收到請求。模式的應用實例【例1】用中介者模式編寫一個“韶關房地產交流平台”程序。

說明:韶關房地產交流平台是“房地產中介公司”提供給“賣方客戶”與“買方客戶”進行信息交流的平台,比較適合用中介者模式來實現。

首先,定義一個中介公司(Medium)接口,它是抽象中介者,它包含了客戶注冊方法 register(Customer member) 和信息轉發方法 relay(String from,String ad);再定義一個韶關房地產中介(EstateMedium)公司,它是具體中介者類,它包含了保存客戶信息的 List 對象,並實現了中介公司中的抽象方法。

然后,定義一個客戶(Qistomer)類,它是抽象同事類,其中包含了中介者的對象,和發送信息的 send(String ad) 方法與接收信息的 receive(String from,Stringad) 方法的接口,由於本程序是窗體程序,所以本類繼承 JPmme 類,並實現動作事件的處理方法 actionPerformed(ActionEvent e)。

最后,定義賣方(Seller)類和買方(Buyer)類,它們是具體同事類,是客戶(Customer)類的子類,它們實現了父類中的抽象方法,通過中介者類進行信息交流,其結構圖如圖 2 所示。


圖2 韶關房地產交流平台的結構圖



程序代碼如下:

  • package mediator;
  • import java.awt.BorderLayout;
  • import java.awt.Container;
  • import java.awt.event.*;
  • import java.util.*;
  • import javax.swing.*;
  • public class DatingPlatform
  • {
  •     public static void main(String[] args)
  •     {
  •         Medium md=new EstateMedium();    //房產中介
  •         Customer member1,member2;
  •         member1=new Seller("張三(賣方)");
  •         member2=new Buyer("李四(買方)");
  •         md.register(member1); //客戶注冊
  •         md.register(member2);
  •     }
  • }
  • //抽象中介者:中介公司
  • interface Medium
  • {
  •     void register(Customer member); //客戶注冊
  •     void relay(String from,String ad); //轉發
  • }
  • //具體中介者:房地產中介
  • class EstateMedium implements Medium
  • {
  •     private List<Customer> members=new ArrayList<Customer>();
  •     public void register(Customer member)
  •     {
  •         if(!members.contains(member))
  •         {
  •             members.add(member);
  •             member.setMedium(this);
  •         }
  •     }
  •     public void relay(String from,String ad)
  •     {
  •         for(Customer ob:members)
  •         {
  •             String name=ob.getName();
  •             if(!name.equals(from))
  •             {
  •                 ((Customer)ob).receive(from,ad);
  •             }
  •         }
  •     }
  • }
  • //抽象同事類:客戶
  • abstract class Customer extends JFrame implements  ActionListener
  • {
  •     private static final long serialVersionUID=-7219939540794786080L;
  •     protected Medium medium;
  •     protected String name;
  •     JTextField SentText;
  •     JTextArea ReceiveArea;
  •     public Customer(String name)
  •     {
  •         super(name);
  •         this.name=name;
  •     }
  •     void ClientWindow(int x,int y)
  •     {
  •         Container cp;
  •         JScrollPane sp;
  •         JPanel p1,p2;
  •         cp=this.getContentPane();
  •         SentText=new JTextField(18);
  •         ReceiveArea=new JTextArea(10,18);
  •         ReceiveArea.setEditable(false);
  •         p1=new JPanel();
  •         p1.setBorder(BorderFactory.createTitledBorder("接收內容:"));
  •         p1.add(ReceiveArea);
  •         sp=new JScrollPane(p1);
  •         cp.add(sp,BorderLayout.NORTH);
  •         p2=new JPanel();
  •         p2.setBorder(BorderFactory.createTitledBorder("發送內容:"));
  •         p2.add(SentText);
  •         cp.add(p2,BorderLayout.SOUTH);
  •         SentText.addActionListener(this);
  •         this.setLocation(x,y);
  •         this.setSize(250, 330);
  •         this.setResizable(false); //窗口大小不可調整
  •         this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  •         this.setVisible(true);
  •     }
  •     public void actionPerformed(ActionEvent e)
  •     {
  •         String tempInfo=SentText.getText().trim();
  •         SentText.setText("");
  •         this.send(tempInfo);
  •     }
  •     public String getName()
  •     {    return name;   }
  •     public void setMedium(Medium medium)
  •     {      this.medium=medium;  }
  •     public abstract void send(String ad);
  •     public abstract void receive(String from,String ad);
  • }
  • //具體同事類:賣方
  • class Seller extends Customer
  • {
  •     private static final long serialVersionUID=-1443076716629516027L;
  •     public Seller(String name)
  •     {
  •         super(name);
  •         ClientWindow(50,100);
  •     }
  •     public void send(String ad)
  •     {
  •         ReceiveArea.append("我(賣方)說: "+ad+"\n");
  •         //使滾動條滾動到最底端
  •         ReceiveArea.setCaretPosition(ReceiveArea.getText().length());
  •         medium.relay(name,ad);
  •     }
  •     public void receive(String from,String ad)
  •     {
  •         ReceiveArea.append(from +"說: "+ad+"\n");
  •         //使滾動條滾動到最底端
  •         ReceiveArea.setCaretPosition(ReceiveArea.getText().length());
  •     }
  • }
  • //具體同事類:買方
  • class Buyer extends Customer
  • {
  •     private static final long serialVersionUID = -474879276076308825L;
  •     public Buyer(String name)
  •     {
  •         super(name);
  •         ClientWindow(350,100);
  •     }
  •     public void send(String ad)
  •     {
  •         ReceiveArea.append("我(買方)說: "+ad+"\n");
  •         //使滾動條滾動到最底端
  •         ReceiveArea.setCaretPosition(ReceiveArea.getText().length());
  •         medium.relay(name,ad);
  •     }
  •     public void receive(String from,String ad)
  •     {
  •           ReceiveArea.append(from +"說: "+ad+"\n");
  •         //使滾動條滾動到最底端
  •         ReceiveArea.setCaretPosition(ReceiveArea.getText().length());
  •     }
  • }




程序的運行結果如圖 3 所示。


圖3 韶關房地產交流平台的運行結果


模式的應用場景前面分析了中介者模式的結構與特點,下面分析其以下應用場景。

  • 當對象之間存在復雜的網狀結構關系而導致依賴關系混亂且難以復用時。
  • 當想創建一個運行於多個類之間的對象,又不想生成新的子類時。

模式的擴展在實際開發中,通常采用以下兩種方法來簡化中介者模式,使開發變得更簡單。

  • 不定義中介者接口,把具體中介者對象實現成為單例。
  • 同事對象不持有中介者,而是在需要的時f矣直接獲取中介者對象並調用。


圖 4 所示是簡化中介者模式的結構圖。


圖4 簡化中介者模式的結構圖



程序代碼如下:

  • package mediator;
  • import java.util.*;
  • public class SimpleMediatorPattern
  • {
  •     public static void main(String[] args)
  •     {
  •         SimpleColleague c1,c2;
  •         c1=new SimpleConcreteColleague1();
  •         c2=new SimpleConcreteColleague2();
  •         c1.send();
  •         System.out.println("-----------------");
  •         c2.send();
  •     }
  • }
  • //簡單單例中介者
  • class SimpleMediator
  • {
  •     private static SimpleMediator smd=new SimpleMediator();
  •     private List<SimpleColleague> colleagues=new ArrayList<SimpleColleague>();
  •     private SimpleMediator(){}
  •     public static SimpleMediator getMedium()
  •     {    return(smd);   }
  •     public void register(SimpleColleague colleague)
  •     {
  •         if(!colleagues.contains(colleague))
  •         {
  •             colleagues.add(colleague);
  •         }
  •     }
  •     public void relay(SimpleColleague scl)
  •     {
  •         for(SimpleColleague ob:colleagues)
  •         {
  •             if(!ob.equals(scl))
  •             {
  •                 ((SimpleColleague)ob).receive();
  •             }
  •         }
  •     }
  • }
  • //抽象同事類
  • interface SimpleColleague
  • {
  •     void receive();
  •     void send();
  • }
  • //具體同事類
  • class SimpleConcreteColleague1 implements SimpleColleague
  • {
  •     SimpleConcreteColleague1(){
  •         SimpleMediator smd=SimpleMediator.getMedium();
  •         smd.register(this);
  •     }
  •     public void receive()
  •     {    System.out.println("具體同事類1:收到請求。");    }
  •     public void send()
  •     {
  •         SimpleMediator smd=SimpleMediator.getMedium();
  •         System.out.println("具體同事類1:發出請求...");
  •         smd.relay(this); //請中介者轉發
  •     }
  • }
  • //具體同事類
  • class SimpleConcreteColleague2 implements SimpleColleague
  • {
  •     SimpleConcreteColleague2(){
  •         SimpleMediator smd=SimpleMediator.getMedium();
  •         smd.register(this);
  •     }
  •     public void receive()
  •     {    System.out.println("具體同事類2:收到請求。");    }
  •     public void send()
  •     {
  •         SimpleMediator smd=SimpleMediator.getMedium();
  •         System.out.println("具體同事類2:發出請求...");
  •         smd.relay(this); //請中介者轉發
  •     }
  • }




程序運行結果如下:具體同事類1:發出請求...具體同事類2:收到請求。-----------------具體同事類2:發出請求...具體同事類1:收到請求。
http://c.biancheng.net/view/1393.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM