中介者模式
内容参考 w3cschoo
分类:行为型设计模式
应用:聊天室
用户要和另外一个人发送消息,需要通过软件进行发送消息。
目录
UML类图
创建用户实体类
User
public class User {
private String name;
public User(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void sendMessage(String message){
ChatRoom.showMessage(this,message);
}
}
创建聊天室
ChatRoom
public class ChatRoom {
public static void showMessage(User user,String message){
System.out.printf("Time:%10s [%8s] : %s\n",new Date(System.currentTimeMillis()).toString(),user.getName(),message);
}
}
运行测试
public class ExecuteMain {
public static void main(String[] args) {
User Dcpnet00 = new User("Dcpnet00");
User Dcpnet01 = new User("Dcpnet01");
Dcpnet00.sendMessage("Hi,01");
Dcpnet01.sendMessage("Hello,00");
}
}
Time:2020-08-31 [Dcpnet00] : Hi,01
Time:2020-08-31 [Dcpnet01] : Hello,00
Process finished with exit code 0