调解人 调停
The major participants of the Mediator pattern are:
Mediator: Defines an interface for communicating with Colleague objects.
ConcreteMediator: implements cooperative behavior by coordinating Colleague objects,
it also knows and maintains its colleagues.
Colleague Classes: Each Colleague class knows its Mediator objects, Each colleague communicates with its mediator whenever it would have otherwise communicated with another colleague.
Mediator Pattern in JDK:
java.util.Timer class schedule XXX() methods.
java Concurrency Executor execute() method.
java.lang.reflect.Method invoke() method.
代码如下
-
package mediatorpattern;
-
-
/* Colleagure A wants to talk, and Colleague B to fight with mediator.
-
* when they do some action(i.e., doSomething()),
-
* they invoke mediator to do that.
-
*/
-
-
-
interface IMediator {
-
public void talk();
-
public void fight();
-
public void registerA(ColleagueA a);
-
public void registerB(ColleagueB b);
-
}
-
-
-
class MyConcreteMediator implements IMediator{
-
ColleagueA talk;
-
ColleagueB fight;
-
-
@Override
-
public void talk(){
-
System.out.println("Mediator is talking");
-
//let the talk colleague do some stuff
-
}
-
-
@Override
-
public void fight(){
-
System.out.println("Mediator is fighting");
-
//let the fight colleague do some stuff
-
}
-
-
@Override
-
public void registerA(ColleagueA a){
-
this.talk = a;
-
}
-
-
@Override
-
public void registerB(ColleagueB b){
-
this.fight = b;
-
}
-
}
-
-
abstract class Colleague{
-
IMediator mediator;
-
public abstract void doSomething();
-
}
-
-
class ColleagueA extends Colleague{
-
public ColleagueA(IMediator mediator){
-
this.mediator = mediator;
-
this.mediator.registerA(this);
-
}
-
-
@Override
-
public void doSomething(){
-
this.mediator.talk();
-
}
-
}
-
-
class ColleagueB extends Colleague{
-
public ColleagueB(IMediator mediator){
-
this.mediator = mediator;
-
this.mediator.registerB(this);
-
}
-
-
@Override
-
public void doSomething(){
-
this.mediator.fight();
-
}
-
}
-
-
public class MediatorPatternDemo{
-
public static void main(String[] args){
-
IMediator mediator = new MyConcreteMediator();
-
-
ColleagueA talkColleague = new ColleagueA(mediator);
-
ColleagueB fightColleague = new ColleagueB(mediator);
-
-
talkColleague.doSomething();
-
fightColleague.doSomething();
-
}
-
}
阅读(574) | 评论(0) | 转发(0) |