public interface Mediator {
void createMediator();
void workAll();
}
//中介。
public class MyMediator implements Mediator {
private User user1;
private User user2;
@Override
public void createMediator() {
user1 = new User1(this);
user2 = new User2(this);
}
//中介带动类对象工作。
@Override
public void workAll() {
user1.work();
user2.work();
}
}
public abstract class User {
private Mediator mediator;
public Mediator getMediator() {
return mediator;
}
public User(Mediator mediator) {
this.mediator = mediator;
}
public abstract void work();
}
public class User1 extends User {
public User1(Mediator mediator) {
super(mediator);
}
@Override
public void work() {
System.out.println("User1 work");
}
}
public class User2 extends User{
public User2(Mediator mediator) {
super(mediator);
}
@Override
public void work() {
System.out.println("User2 work");
}
}
public class Test {
public static void main(String[] args) {
try {
Test test = new Test();
} catch (Exception e) {
e.printStackTrace();
}
}
public Test() {
//中介模式中,隐藏了不同类对象的,换言之,类对象的修改只需要对中介负责即可。
Mediator mediator = new MyMediator();
mediator.createMediator();
mediator.workAll();
}
}
输出:
User1 work
User2 work