中介者模式
Posted yfy-
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了中介者模式相关的知识,希望对你有一定的参考价值。
一、定义
中介者模式(Mediator),用一个中介对象来封装一系列的对象交互。中介者使各对象不需要显式地相互引用,从而使其耦合松散,而且可以独立地改变它们之间的交互。
二、示例代码
public abstract class Mediator {
public abstract void send(String message,Colleague colleague);
}
public class ConcreteMediator extends Mediator {
private ConcreteColleague1 concreteColleague1;
private ConcreteColleague2 concreteColleague2;
public void setConcreteColleague1(ConcreteColleague1 concreteColleague1) {
this.concreteColleague1 = concreteColleague1;
}
public void setConcreteColleague2(ConcreteColleague2 concreteColleague2) {
this.concreteColleague2 = concreteColleague2;
}
@Override
public void send(String message, Colleague colleague) {
if (colleague==concreteColleague1){
concreteColleague2.inform(message);
}
else {
concreteColleague1.inform(message);
}
}
}
public class ConcreteColleague1 extends Colleague {
public ConcreteColleague1(Mediator mediator) {
super(mediator);
}
public void send(String message){
mediator.send(message,this);
}
public void inform(String message)
{
System.out.println("同事1得到消息"+message);
}
}
public class ConcreteColleague2 extends Colleague {
public ConcreteColleague2(Mediator mediator) {
super(mediator);
}
public void send(String message){
mediator.send(message,this);
}
public void inform(String message)
{
System.out.println("同事2得到消息"+message);
}
}
public abstract class Colleague {
protected Mediator mediator;
public Colleague(Mediator mediator) {
this.mediator = mediator;
}
}
public class Client {
public static void main(String[] args) {
ConcreteMediator mediator=new ConcreteMediator();
ConcreteColleague1 concreteColleague1=new ConcreteColleague1(mediator);
ConcreteColleague2 concreteColleague2=new ConcreteColleague2(mediator);
mediator.setConcreteColleague1(concreteColleague1);
mediator.setConcreteColleague2(concreteColleague2);
mediator.send("hello",concreteColleague1);
mediator.send("hi",concreteColleague2);
}
}
以上是关于中介者模式的主要内容,如果未能解决你的问题,请参考以下文章