解决的问题
所有做过前端的人都应该使用过该模式。你要开发一个界面,界面由选项列表(OptionList),文本框(TextBox)和按钮(Button)组成。在选项列表完成选择后,文本框就会显示选择的内容,按钮会变成可点击的。
代码
EventHandler
:
package com.cong.designpattern.mediator;
public interface EventHandler {
public void handle();
}
UIControl
:
package com.cong.designpattern.mediator;
import java.util.ArrayList;
import java.util.List;
public class UIControl {
private List<EventHandler> eventHandlers = new ArrayList<>();
public void addEventHandler(EventHandler eventHandler) {
this.eventHandlers.add(eventHandler);
}
public void removeEventHandler(EventHandler eventHandler) {
this.eventHandlers.remove(eventHandler);
}
protected void notifyEventHandlers() {
for (EventHandler eventHandler : this.eventHandlers) eventHandler.handle();
}
}
OptionList
:
package com.cong.designpattern.mediator;
public class OptionList extends UIControl {
private String selection;
public String getSelection() {
return selection;
}
public void setSelection(String selection) {
this.selection = selection;
this.notifyEventHandlers();
}
}
TextBox
:
package com.cong.designpattern.mediator;
public class TextBox extends UIControl {
private String content;
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
this.notifyEventHandlers();
}
}
Button
:
package com.cong.designpattern.mediator;
public class Button extends UIControl{
private boolean isEnabled = false;
public boolean isEnabled() {
return isEnabled;
}
public void setEnabled(boolean enabled) {
isEnabled = enabled;
this.notifyEventHandlers();
}
}
DialogBox
:
package com.cong.designpattern.mediator;
public class DialogBox {
private Button button = new Button();
private TextBox textBox = new TextBox();
private OptionList optionList = new OptionList();
public DialogBox() {
this.optionList.addEventHandler(() -> {
String selection = this.optionList.getSelection();
this.textBox.setContent(selection);
this.button.setEnabled(selection != null && !selection.isEmpty());
});
}
public void simulateUserInteraction() {
this.optionList.setSelection("Hello Mediator Pattern!");
System.out.println("Text box content: " + this.textBox.getContent());
System.out.println("Button is enable: " + this.button.isEnabled());
}
}
Test code:
DialogBox dialogBox = new DialogBox();
dialogBox.simulateUserInteraction();
UML
![](https://img.haomeiwen.com/i4633505/905d369b42eb98fd.png)
网友评论