概念:用一个中介对象来封装一系列的对象交互。中介者使各对象不需要显示地相互引用,从而使其耦合松散,而且可以独立地改变它们之间的交互。
核心:处理多对多关系,对对象如何协作进行了抽象,集中控制
缺点:导致中介者类复杂性上升

中介者模式结构图

image.png
java代码

  1. public class MediatorTest {
  2. public static void main(String[] args) {
  3. ConcreteMediator concreteMediator = new ConcreteMediator();
  4. ConcreteColleague1 concreteColleague1 = new ConcreteColleague1(concreteMediator);
  5. ConcreteColleague2 concreteColleague2 = new ConcreteColleague2(concreteMediator);
  6. concreteMediator.setConcreteColleague1(concreteColleague1);
  7. concreteMediator.setConcreteColleague2(concreteColleague2);
  8. concreteColleague1.Send();
  9. concreteColleague2.Send();
  10. }
  11. }
  12. //中介者
  13. public abstract class Mediator {
  14. public abstract void Send(String message, Colleague colleague);
  15. }
  16. //中介者实现类
  17. public class ConcreteMediator extends Mediator{
  18. private ConcreteColleague1 concreteColleague1;
  19. private ConcreteColleague2 concreteColleague2;
  20. public void setConcreteColleague1(ConcreteColleague1 concreteColleague1){
  21. this.concreteColleague1 = concreteColleague1;
  22. }
  23. public void setConcreteColleague2(ConcreteColleague2 concreteColleague2){
  24. this.concreteColleague2 = concreteColleague2;
  25. }
  26. @Override
  27. public void Send(String message, Colleague colleague) {
  28. if (colleague == concreteColleague1){
  29. concreteColleague2.Notify(message);
  30. }else{
  31. concreteColleague1.Notify(message);
  32. }
  33. }
  34. }
  35. //抽象同事类
  36. public abstract class Colleague {
  37. Mediator mediator;
  38. public Colleague(Mediator mediator){
  39. this.mediator = mediator;
  40. }
  41. public abstract void Send();
  42. public abstract void Notify(String message);
  43. }
  44. //同事1
  45. public class ConcreteColleague1 extends Colleague {
  46. public ConcreteColleague1(Mediator mediator) {
  47. super(mediator);
  48. }
  49. @Override
  50. public void Send() {
  51. mediator.Send("我是同事1发送的消息", this);
  52. }
  53. @Override
  54. public void Notify(String message) {
  55. System.out.println("同事1得到信息:" + message);
  56. }
  57. }
  58. //同事2
  59. public class ConcreteColleague2 extends Colleague{
  60. public ConcreteColleague2(Mediator mediator) {
  61. super(mediator);
  62. }
  63. @Override
  64. public void Send() {
  65. mediator.Send("我是同事2发送的消息", this);
  66. }
  67. @Override
  68. public void Notify(String message) {
  69. System.out.println("同事2得到信息:" + message);
  70. }
  71. }