中介模式:
用一箇中介對象(中介者)來封裝一系列的對象交互,中介者使各對象不須要顯式地相互引用,從而使其耦合鬆散,
並且能夠獨立地改變它們之間的交互。中介者模式又稱爲調停者模式,它是一種對象行爲型模式。java
結構圖:
markdown
示例類圖:
ide
示例代碼:測試
public interface Mediator {
public abstract void work(Colleague colleague);
}
public class ConcreteMediator implements Mediator {
private CDDriver cdDriver;
private SoundCard soundCard;
@Override
public void work(Colleague colleague) {
if (cdDriver == colleague) {
cdDriver.readSound();
} else if (soundCard == colleague) {
soundCard.playSound();
}
}
public void setCdDriver(CDDriver cdDriver) {
this.cdDriver = cdDriver;
}
public void setSoundCard(SoundCard soundCard) {
this.soundCard = soundCard;
}
}
// Colleague 同事類
public abstract class Colleague {
protected Mediator mediator;
public Colleague(Mediator mediator) {
this.mediator = mediator;
}
public abstract void work();
}
// ConcreteMediator
public class CDDriver extends Colleague {
public CDDriver(Mediator mediator) {
super(mediator);
}
@Override
public void work() {
mediator.work(this);
}
public void readSound() {
System.out.println("CDDriver readSound.");
}
}
public class SoundCard extends Colleague {
public SoundCard(Mediator mediator) {
super(mediator);
}
@Override
public void work() {
mediator.work(this);
}
public void playSound() {
System.out.println("SoundCard playSound.");
}
}
// 測試
public class MediatorTest {
public static void main(String[] args) {
ConcreteMediator mediator = new ConcreteMediator();
CDDriver cdDriver = new CDDriver(mediator);
SoundCard soundCard = new SoundCard(mediator);
mediator.setCdDriver(cdDriver);
mediator.setSoundCard(soundCard);
cdDriver.work();
soundCard.work();
}
}
角色:this
Mediator :中介者接口/抽象類。
在裏面定義了各個同事之間相互交互所須要的方法,
能夠是公共的方法,如Change方法,也能夠是小範圍的交互方法。spa
ConcreteMediator :具體的中介者實現對象。
它須要瞭解併爲維護每一個同事對象,並負責具體的協調各個同事對象的交互關係。code
Colleague :同事類的定義,一般實現成爲抽象類。
主要負責約束同事對象的類型,並實現一些具體同事類之間的公共功能,好比,每一個具體同事類都應該知道中介者對象,
也就是每一個同事對象都會持有中介者對象的引用,這個功能可定義在這個類中。對象
ConcreteColleague :具體的同事類,實現本身的業務。
須要與其餘同事對象交互時,就通知中介對象,中介對象會負責後續的交互。接口