中介者模式
中介者
主要是通过中介对象来封装对象之间的关系
同时通过引用中介者对象来减少系统对象之间关系,提高了对象的可复用和系统的可扩展性。
抽象中介者(Mediator)角色:
它是中介者的接口,提供了同事对象注册与转发同事对象信息的抽象方法。
具体中介者(ConcreteMediator)角色:
实现中介者接口,定义一个 List 来管理同事对象,协调各个同事角色之间的交互关系,因此它依赖于同事角色。
抽象同事类(Colleague)角色:
定义同事类的接口,保存中介者对象,提供同事对象交互的抽象方法,实现所有相互影响的同事类的公共功能。
具体同事类(Concrete Colleague)角色:
是抽象同事类的实现者,当需要与其他同事对象交互时,由中介者对象负责后续的交互。
1 import java.util.ArrayList; 2 3 public class Mediator { 4 public static void main(String[] args) { 5 Mediatoring q = new ConcreteMediator(); 6 Colleague a = new ConcreteColleague1(); 7 Colleague b = new ConcreteColleague2(); 8 q.register(a); 9 q.register(b); 10 a.retransmission(); 11 } 12 } 13 14 //抽象中介者 15 abstract class Mediatoring { 16 //注册会员 17 public abstract void register(Colleague colleague); 18 19 //通知 20 public abstract void notify(Colleague cl); //转发 21 } 22 23 //具体中介者 24 class ConcreteMediator extends Mediatoring { 25 26 //会员 27 private ArrayList<Colleague> arr = new ArrayList<Colleague>(); 28 29 @Override 30 public void register(Colleague colleague) { 31 if (!arr.contains(colleague)) { 32 arr.add(colleague); 33 colleague.setMdiatoring(this); 34 } 35 } 36 37 @Override 38 public void notify(Colleague cl) { 39 for (Colleague co : arr) { 40 if (!co.equals(cl)) { 41 co.response(); 42 } 43 } 44 } 45 } 46 47 //抽象会员 48 abstract class Colleague { 49 //中介 50 private Mediatoring mdiatoring; 51 52 public Mediatoring getMdiatoring() { 53 return mdiatoring; 54 } 55 56 public void setMdiatoring(Mediatoring mdiatoring) { 57 this.mdiatoring = mdiatoring; 58 } 59 60 //转发 61 public abstract void retransmission(); 62 63 //回应 64 public abstract void response(); 65 } 66 67 //具体会员 68 class ConcreteColleague1 extends Colleague { 69 70 @Override 71 public void retransmission() { 72 getMdiatoring().notify(this); 73 } 74 75 @Override 76 public void response() { 77 System.out.println("一号收到"); 78 } 79 } 80 81 class ConcreteColleague2 extends Colleague { 82 83 @Override 84 public void retransmission() { 85 getMdiatoring().notify(this); 86 } 87 88 @Override 89 public void response() { 90 System.out.println("二号收到"); 91 } 92 }
原文:https://www.cnblogs.com/loveer/p/11279585.html