/* * 本例为建立一个虚拟聊天室。允许会员通过该聊天室进行信息交流,普通会员(Common Member)可以给其他会员发 * 送文本信息,钻石会员(Diamond Member)除了可以发送文本消息外,还可以发送图片。 */ // Mediator - 抽象中介者 public abstract class AbstractChatroom { private List<Member> members; public AbstractChatroom() { this.members = new ArrayList<Member>(); } public void register(Member member) { this.members.add(member); } public List<Member> getMembers() { return this.members; } public abstract void sendText(String text); public abstract void sendImage(Photo photo); }
// ConcreteMediator - 具体中介者 public class ChatGroup extends AbstractChatroom { public void register(Member member) { super.register(member); member.setChatroom(this); } public void sendText(String text) { List<Member> members = getMembers(); for (Member member: members) { member.receiveText(text); } } public void sendImage(Photo photo) { List<Member> members = getMembers(); for (Member member: members) { member.receiveImage(photo); } } }
// Colleague - 抽象同事类 public abstract class Member { private String name; private AbstractChatroom chatroom; public Member(String name) { this.name = name; } public void setChatroom(AbstractChatroom chatroom) { this.chatroom = chatroom; } public AbstractChatroom getChatroom() { return this.chatroom; } public void receiveImage(Photo photo) { System.out.println(name + " receive photo: " + photo.getName()); } public void receiveText(String text) { System.out.println(name + " receive text: " + text); } public void sendImage(Photo photo) { throw new IllegalStateException("you don't have an access"); } public void sendText(String text) { this.chatroom.sendText(text); } }
// ConcreteColleague - 具体同事类 // 普通会员 public class CommonMember extends Member { public CommonMember(String name) { super(name); } public void sendText(String text) { getChatroom().sendText(text); } }
// 钻石会员 public class DiamondMember extends Member { public DiamondMember(String name) { super(name); } public void sendText(String text) { getChatroom().sendText(text); } public void sendImage(Photo photo) { getChatroom().sendImage(photo); } }
// 测试类 public class Text { public static void main(String[] args) { AbstractChatroom chatroom = new ChatGroup(); Member common = new CommonMember("Peter"); Member diamond = new DiamondMember("Mary"); chatroom.register(common); chatroom.register(diamond); common.sendText("Hello"); diamond.sendImage(new Photo("Cool")); System.out.println("END"); } }