- Client:
public class Client { public static void main(String[] args) { Mediator mediator = new ConcreteMediator(); Colleague colleague = new ConcreteColleague(); mediator.register(colleague); colleague.send(); } }
- Mediator:
public interface Mediator { void register(Colleague colleague); void relay(Colleague colleague); }
- ConcreteMediator:
public class ConcreteMediator implements Mediator{ private Listcolleagues = new ArrayList<>(); @Override public void register(Colleague colleague) { if (!colleagues.contains(colleague)) { colleague.setMediator(this); colleagues.add(colleague); } } @Override public void relay(Colleague colleague) { colleague.receive(); } }
- Colleague:
public abstract class Colleague { protected Mediator mediator = null; public void setMediator(Mediator mediator) { this.mediator = mediator; } public abstract void receive(); public abstract void send(); }
- ConcreteColleague:
public class ConcreteColleague extends Colleague{ @Override public void receive() { } @Override public void send() { mediator.relay(this); } }三、角色介绍
- Client(客户端):
客户端角色,程序的调用者。 - Mediator(中介者):
该角色负责定义与Colleague角色进行通信和做出决定的接口。 - ConcreteMediator(具体的中介者):
该角色负责实现Mediator角色的接口,负责实际做出决定。 - Colleague(同事):
该角色负责定义与Mediator角色进行通信的接口。 - ConcreteColleague(具体的同事):
该角色负责实现Colleague角色的接口。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)