【设计模式-中介者模式】
// Mediator interface
interface Mediator {
void send(String message, Colleague colleague);
}
// Concrete Mediator
class ChatMediator implements Mediator {
private List<Colleague> colleagues = new ArrayList<>();
public void addColleague(Colleague colleague) {
colleagues.add(colleague);
}
@Override
public void send(String message, Colleague colleague) {
for (Colleague c : colleagues) {
// Prevent sending message back to the sender
if (c != colleague) {
c.receive(message);
}
}
}
}
// Colleague interface
abstract class Colleague {
protected Mediator mediator;
public Colleague(Mediator mediator) {
this.mediator = mediator;
}
public abstract void send(String message);
public abstract void receive(String message);
}
// Concrete Colleague
class User extends Colleague {
private String name;
public User(Mediator mediator, String name) {
super(mediator);
this.name = name;
}
@Override
public void send(String message) {
System.out.println(name + ": Sending message: " + message);
mediator.send(message, this);
}
@Override
public void receive(String message) {
System.out.println(name + ": Received message: " + message);
}
}
// Client code
public class MediatorPatternDemo {
public static void main(String[] args) {
ChatMediator mediator = new ChatMediator();
User user1 = new User(mediator, "Alice");
User user2 = new User(mediator, "Bob");
mediator.addColleague(user1);
mediator.addColleague(user2);
user1.send("Hello Bob!");
user2.send("Hi Alice!");
}
}