场景:玩家发送消息,在聊天室显示。
首先设计一个聊天室接口,然后是具体聊天室类实现该接口,接着设计一个用户抽象类,聚合聊天室接口,再设计一个具体用户类继承该抽象类,最后是客户端主类。
聊天室接口:
package com.freshbin.pattern.mediator.myexample.chat.chatroom;
import com.freshbin.pattern.mediator.myexample.chat.person.User;
/**
* 聊天室接口
*
* @author freshbin
* @date 2019年1月19日 下午8:05:04
*/
public interface ChatRoom {
public void showMsg(User user);
}
具体聊天室接口:
package com.freshbin.pattern.mediator.myexample.chat.chatroom;
import com.freshbin.pattern.mediator.myexample.chat.person.User;
/**
* LOL聊天室
*
* @author freshbin
* @date 2019年1月19日 下午8:12:09
*/
public class LOLChatRoom implements ChatRoom {
@Override
public void showMsg(User user) {
System.out.println(user.getName() + ":" + user.getMessage());
}
}
抽象用户类:
package com.freshbin.pattern.mediator.myexample.chat.person;
import com.freshbin.pattern.mediator.myexample.chat.chatroom.ChatRoom;
/**
* 用户抽象类
*
* @author freshbin
* @date 2019年1月19日 下午8:07:07
*/
public abstract class User {
private String name;
private String message;
protected ChatRoom chatRoom;
public User(ChatRoom chatRoom, String name) {
this.name = name;
this.chatRoom = chatRoom;
}
public void sendMsg(String msg) {
this.setMessage(msg);
chatRoom.showMsg(this);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
具体用户类:
package com.freshbin.pattern.mediator.myexample.chat.person;
import com.freshbin.pattern.mediator.myexample.chat.chatroom.ChatRoom;
/**
* 普通用户
*
* @author freshbin
* @date 2019年1月19日 下午8:09:58
*/
public class NormalUser extends User {
public NormalUser(ChatRoom chatRoom, String name) {
super(chatRoom, name);
}
}
客户端主类:
package com.freshbin.pattern.mediator.myexample;
import com.freshbin.pattern.mediator.myexample.chat.chatroom.ChatRoom;
import com.freshbin.pattern.mediator.myexample.chat.chatroom.LOLChatRoom;
import com.freshbin.pattern.mediator.myexample.chat.person.NormalUser;
import com.freshbin.pattern.mediator.myexample.chat.person.User;
/**
* 中介者模式
*
* @author freshbin
* @date 2019年1月19日 下午8:03:34
*/
public class MediatorPatternDemo {
public static void main(String[] args) {
ChatRoom chatRoom = new LOLChatRoom();
User user01 = new NormalUser(chatRoom, "普通玩家一");
user01.sendMsg("我后羿贼强!");
User user02 = new NormalUser(chatRoom, "普通玩家二");
user02.sendMsg("我喷队友贼快!");
}
}
效果图: