你没有指定一种语言,所以我会尽可能保持通用。
abstract class Participant {
public string Notify(string message);
}
class WidgetOne extends Participant {
Mediator _mediator;
public WidgetOne(Mediator theMediator){
_mediator = theMediator;
}
public string Notify(string message){
#do whatever
}
public string Talk(string message){
return _mediator.Talk(message, this);
}
}
class WidgetTwo extends Participant {
Mediator _mediator;
public WidgetOne(Mediator theMediator){
_mediator = theMediator;
}
public string Notify(string message){
#do whatever
}
public string Talk(string message){
return _mediator.Talk(message, this);
}
}
class Mediator {
WidgetOne _widgetOne;
WidgetTwo _widgetTwo;
public void setWidgetOne(WidgetOne theWidget){
_wiidgetOne = theWidget;
}
public void setWidgetTwo(WidgetTwo theWidget){
_wiidgetTwo = theWidget;
}
public string Talk(string message, Participant p){
#make sure you do the correct ==/equals/etc.
if(p == _widgetOne){
response = _widgetTwo.Notify(message);
}else if (p == _widgetTwo){
response = _widgetOne.Notify(message);
}
return response;
}
}
class Main {
public void run(){
Mediator theMediator = new Mediator();
WidgetOne one = new WidgetOne(theMediator);
WidgetTwo two = new WidgetTwo(theMediator);
theMediator.setWidgetOne(one);
theMediator.setWidgetTwo(two);
one.Talk("hi there");
}
}
因此,在高级别上,您有 2 个参与者想要交谈,因此您需要设置一个通用界面来这样做。
我们创建一个方法调用 Notify(message); 这基本上是你的沟通渠道。
为了进行设置,我们实例化了一个调解器,然后实例化两个参与者,将它们传递给调解器。
最后一步 insetup 是注入/设置中介参与者。在我们的例子中,我们只使用简单的设置器。
当需要进行通信时,每个参与者只需调用中介,将消息和自身作为参数传递。
调解员看看谁联系了他们,然后打电话给相反的人。
如果您有任何问题,请告诉我,这种模式显然有很多变体,所以如果您还想看到其他内容,请告诉我。
小心。