Java23种设计模式-行为型模式之中介者模式

// 中介者接口 interface Mediator { void sendMessage(String message, User user); } // 具体中介者 class ChatRoom implements Mediator { public void sendMessage(String message, User user) { System.out.println("From " + user.getName() + " to all: " + message); } } // 同事类接口 abstract class User { protected String name; protected Mediator mediator; public User(String name, Mediator mediator) { this.name = name; this.mediator = mediator; } public abstract void receiveMessage(String message); } // 具体同事类 class ConcreteUser extends User { public ConcreteUser(String name, Mediator mediator) { super(name, mediator); } public void receiveMessage(String message) { System.out.println("To " + name + " " + message); } public void sendMessage(String message) { mediator.sendMessage(message, this); } } // 客户端 public class Client { public static void main(String[] args) { Mediator mediator = new ChatRoom(); User user1 = new ConcreteUser("User1", mediator); User user2 = new ConcreteUser("User2", mediator); ((ConcreteUser) user1).sendMessage("Hello, User2!"); ((ConcreteUser) user2).sendMessage("Hi, User1!"); } }
上一篇:Linux进程


下一篇:解决Blender导出FBX文件到Unity坐标轴错误的问题