1.概述
该模式在Head First中没有介绍,它用于通过一个中介者完成对象间通信的解耦。当代码中出现大量有着其他对象信息的对象时就可以使用这个模式。
在这个模式中,有如下的参与者:
中介者(Mediator):抽象定义了“同事”(colleagues,稍后有定义)们通信的接口。
具体中介者(Concrete Mediator):实现了“同事”间的通信接口。
同事(Colleague):参与通信的实体抽象。
具体同事(Concrete Colleague):实现的参与通信的实体。
简单的说,通过同事持有中介者(其中完成了同事间通信的接口)的引用而实现了同事间的通信。
其中,中介者和同事的抽象并不是必须的,只是为了面向接口编程的抽象需要。
2.实例
我们用一个原型系统简单演示一下这个模式
首先我们定义一个抽象中介者,其中有通信接口Send:
1: abstract class Mediator2: {3: // Methods4: abstract public void Send( String message,Colleague colleague );5: }然后我们对其进行实现:
1: class ConcreteMediator extends Mediator2: {3: // Fields4: private ConcreteColleague1 colleague1;5: private ConcreteColleague2 colleague2;6:7: // Properties8: public void setColleague1(ConcreteColleague1 col)9: {10: this.colleague1 = col;11: }12:13: public void setColleague2 (ConcreteColleague2 col)14: {15: this.colleague2=col;16: }17:18: // Methods19: public void Send( String message,20: Colleague colleague )21: {22: if( colleague == colleague1 )23: colleague2.Notify( message );24: else25: colleague1.Notify( message );26: }27: }28:中介者里有通信的双方同事,在同事里有一个Notify方法,表示提示收到一个消息。
然后我们定义一个抽象同事类:
1: abstract class Colleague2: {3: // Fields4: protected Mediator mediator;5:6: // Constructors7: public Colleague( Mediator mediator )8: {9: this.mediator = mediator;10: }11:同事类中要持有中介者的引用。
进而我们定义两个具体的同事:
1: class ConcreteColleague1 extends Colleague2: {3: // "Constructors"4: public ConcreteColleague1( Mediator mediator ) {5: super(mediator);6: }7:8: // Methods9: public void Send( String message )10: {11: mediator.Send( message, this );12: }13:14: public void Notify( String message )15: {16: System.out.println( "Colleague1 gets message: "17: + message );18: }19: }1: class ConcreteColleague2 extends Colleague2: {3: // Constructors4: public ConcreteColleague2( Mediator mediator ) {5: super(mediator);6: }7:8: // Methods9: public void Send( String message )10: {11: mediator.Send( message, this );12: }13: public void Notify( String message )14: {15: System.out.println( "Colleague2 gets message: "16: + message );17: }18: }现在我们开始使用这个中介者完成两个同事间的通信:
1: public class Client2: {3: public static void main(String[] args)4: {5: ConcreteMediator m = new ConcreteMediator();6: ConcreteColleague1 c1 = new ConcreteColleague1( m );7: ConcreteColleague2 c2 = new ConcreteColleague2( m );8:9: m.setColleague1(c1);10: m.setColleague2(c2);11:12: c1.Send( "How are you?" );13: c2.Send( "Fine, thanks" );14: }15: }3.UML总结