設計模式練習(15)——中介者模式
阿新 • • 發佈:2019-01-02
中介者模式
一、題目:
某軟體公司需要開發一套圖形使用者介面類庫,該類庫包含若干個預定義的窗格物件,例如TextPane,ListPane,GraphicPane,視窗之間不允許直接呼叫,具有該類庫的應用由一個包含一組窗格的視窗(Window)組成,視窗需要協調窗格之間的行為,採用中介者模式收集系統
(1)繪製中介者模式結構檢視
(2)給出例項類圖並實現程式碼。
二、所用模式結構檢視:
三、例項類圖:
四、例項實現程式碼:
(因為區分,所以在類的前面加了Gj19)
抽象中介者 -視窗
package gjMediatorPattern;
/**
* 抽象中介者 -視窗
* @author gongjian
*
*/
public abstract class Gj19Window {
public abstract void doSomeThing(Gj19Pane pane,String order);
}
具體中介者
package gjMediatorPattern;
/**
* 具體中介者
* @author gongjian
*/
public class Gj19ConcreteWindow extends Gj19Window{
private Gj19GraphicPane graphicPane;
private Gj19ListPane listPane;
private Gj19TextPane textPane;
public Gj19GraphicPane getGraphicPane() {
return graphicPane;
}
public void setGraphicPane(Gj19GraphicPane graphicPane) {
this.graphicPane = graphicPane;
}
public Gj19ListPane getListPane() {
return listPane;
}
public void setListPane (Gj19ListPane listPane) {
this.listPane = listPane;
}
public Gj19TextPane getTextPane() {
return textPane;
}
public void setTextPane(Gj19TextPane textPane) {
this.textPane = textPane;
}
public Gj19ConcreteWindow(Gj19GraphicPane graphicPane,
Gj19ListPane listPane,Gj19TextPane textPane) {
this.graphicPane = graphicPane;
this.listPane = listPane;
this.textPane = textPane;
}
@Override
public void doSomeThing(Gj19Pane pane, String order) {
pane.update(order);
}
}
抽象同事類-視窗格
package gjMediatorPattern;
/**
* 抽象同事類-視窗格
*
* @author gongjian
*
*/
public abstract class Gj19Pane {
private Gj19Window window;
public Gj19Window getWindow() {
return window;
}
public void setWindow(Gj19Window window) {
this.window = window;
}
public abstract void update(String order);
}
具體同事類
package gjMediatorPattern;
/**
* 具體同事類
* @author gong
*
*/
public class Gj19TextPane extends Gj19Pane{
@Override
public void update(String order) {
System.out.println("TextPane接收到指令"+order);
}
}
具體同事類
package gjMediatorPattern;
/**
* 具體同事類
* @author gong
*
*/
public class Gj19GraphicPane extends Gj19Pane{
@Override
public void update(String order) {
System.out.println("GraphicPane接收到指令"+order);
}
}
具體同事類
package gjMediatorPattern;
/**
* 具體同事類
* @author gong
*
*/
public class Gj19ListPane extends Gj19Pane{
@Override
public void update(String order) {
System.out.println("ListPane接收到指令"+order);
}
}
中介者模式客戶端
package gjMediatorPattern;
/**
* 中介者模式客戶端
* @author gong
*
*/
public class Client {
public static void main(String[] args) {
Gj19ListPane gj19ListPane =new Gj19ListPane();
Gj19TextPane gj19TextPane = new Gj19TextPane();
Gj19GraphicPane gj19GraphicPane = new Gj19GraphicPane();
Gj19ConcreteWindow concreteWindow = new Gj19ConcreteWindow(gj19GraphicPane,gj19ListPane, gj19TextPane);
System.out.println("============系統發出請求===============");
concreteWindow.doSomeThing(gj19GraphicPane, "影象放大1.2倍");
concreteWindow.doSomeThing(gj19TextPane, "文字縮小到原來的0.8倍");
concreteWindow.doSomeThing(gj19ListPane, "列表左移10px");
System.out.println("=============系統結束===================");
}
}
五、執行結果: