- 抽象中介者
public abstract class AbstractMediator {
protected AbstractColleague c1;
protected AbstractColleague c2;
public AbstractColleague getC1() {
return c1;
}
public void setC1(AbstractColleague c1) {
this.c1 = c1;
}
public AbstractColleague getC2() {
return c2;
}
public void setC2(AbstractColleague c2) {
this.c2 = c2;
}
//中介者处理方法
protected abstract void handleRequest();
}
- 抽象中介者实现类
public class ConcreteMediator extends AbstractMediator {
@Override
protected void handleRequest() {
super.c1.doSomething();
super.c2.doSomething();
}
}
- 同事类抽象对象
public abstract class AbstractColleague {
protected AbstractMediator mediator;
public AbstractColleague(AbstractMediator mediator) {
this.mediator = mediator;
}
public abstract void doSomething() ;
public abstract void deputeMethod() ;
}
- 同事类抽象对象实现类
public class ConcreteColleague extends AbstractColleague {
public ConcreteColleague(AbstractMediator mediator) {
super(mediator);
}
@Override
public void doSomething() {
//普通方法业务处理
}
@Override
public void deputeMethod() {
//委托给中介者处理
super.mediator.handleRequest();
}
}
- 场景使用
//创建中介者
AbstractMediator mediator = new ConcreteMediator();
//创建同事类对象
AbstractColleague colleague1 = new ConcreteColleague(mediator);
//同事类对象在中介者对象中注册
mediator.setC1(colleague1);
//同事类对象通过中介者进行处理逻辑
colleague1.deputeMethod();