步骤一:创建 中介者 Mediator
public interface Mediator {
//创建中介者
public void createMediator();
public void workAll();
}
步骤二:建立具体中介者 实现者
public class MyMediator implements Mediator {
private User user1;
private User user2;
public User getUser1() {
return user1;
}
public User getUser2() {
return user2;
}
@Override
public void createMediator() {
user1=new User1(this);
user2=new User2(this);
}
@Override
public void workAll() {
user1.work();
user2.work();
}
}
步骤三:建立同事类接口 User
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);
}
public void work() {
System.out.println("user1 执行工作");
}
}
public class User2 extends User {
public User2(Mediator mediator) {
super(mediator);
}
public void work() {
System.out.println("user2执行工作");
}
}
步骤五:测试
public class Test {
public static void main(String[] args) {
Mediator mediator=new MyMediator();
mediator.createMediator();
mediator.workAll();
}
}