中介者模式定义:用一个中介对象来封装一系列的对象交互,中介者使各对象不需要显式地相互引用,从而使其耦合松散,而且可以独立地改变它们之间的交互。中介者模式又称为调停者模式。(对象行为型模式)
中介者模式主要包含4个角色:
- package Mediator.example;
- //抽象中介者
- public abstract class Mediator {
- /**注册同事类*/
- public abstract void register(Colleague colleague);
-
- /**处理接收逻辑*/
- public abstract void operation(Colleague colleague);
- }
- package Mediator.example;
- import java.util.List;
- import java.util.ArrayList;
- //具体中介者类
- public class ConcreteMediator extends Mediator {
-
- private List
colleagues = new ArrayList(); - @Override
- public void register(Colleague colleague) {
- // TODO Auto-generated method stub
- if (!colleagues.contains(colleague)) {
- colleagues.add(colleague);
- colleague.setMediator(this);
- }
- }
-
- @Override
- public void operation(Colleague colleague) {
- // TODO Auto-generated method stub
- for (Colleague coll : colleagues) {
- if (!coll.equals(colleague)) {
- coll.receive();
- }
- }
- }
-
- }
- package Mediator.example;
- //抽象同事类
- public abstract class Colleague {
- protected Mediator mediator;
-
- public void setMediator(Mediator mediator) {
- this.mediator = mediator;
- }
-
- public abstract void receive();
-
- public abstract void send();
- }
- package Mediator.example;
- //具体同事类1
- public class ConcreteColleague1 extends Colleague {
-
- @Override
- public void receive() {
- // TODO Auto-generated method stub
- System.out.println("具体同事类 ConcreteColleague1 接收请求");
- }
-
- @Override
- public void send() {
- // TODO Auto-generated method stub
- System.out.println("具体同事类 ConcreteColleague1 发送请求");
- /*中介者进行转发*/
- mediator.operation(this);
- }
-
- }
- package Mediator.example;
- //具体同事类2
- public class ConcreteColleague2 extends Colleague {
-
- @Override
- public void receive() {
- // TODO Auto-generated method stub
- System.out.println("具体同事类 ConcreteColleague2 接收到请求");
- }
-
- @Override
- public void send() {
- // TODO Auto-generated method stub
- System.out.println("具体同事类 ConcreteColleague2 发送请求");
- mediator.operation(this);
- }
-
- }
- package Mediator.example;
-
- public class Client {
- public static void main(String[] args) {
- Mediator concreteMediator = new ConcreteMediator();
- Colleague concreteColleague1 = new ConcreteColleague1();
- Colleague concreteColleague2 = new ConcreteColleague2();
- concreteMediator.register(concreteColleague1);
- concreteMediator.register(concreteColleague2);
- concreteColleague1.send();
- concreteColleague2.send();
-
- }
- }