-
定义:
定义一个中介对象来封装一系列对象之间的交互,使原有对象之间的耦合松散,且可以独立地改变它们之间的交互。 -
特点:
- 降低了对象之间的耦合性,使得对象易于独立地被复用。(优点)
- 将对象间的一对多关联转变为一对一的关联,提高系统的灵活性,使得系统易于维护和扩展。(优点)
- 当同事类太多时,中介者的职责将很大,它会变得复杂而庞大,以至于系统难以维护。(缺点)
-
通常适用场景:
- 当对象之间存在复杂的网状结构关系而导致依赖关系混乱且难以复用时。
- 当想创建一个运行于多个类之间的对象,又不想生成新的子类时。
-
demo代码:
- 中介者类
//中介者抽象类 public interface Mediator{ void register(Colleague colleague);//注册 void relay(Colleague colleague); //转发 } //中介者实现类 public class MediatorImpl implements Mediator{ private List<Colleague> colleagues=new ArrayList<>(); @Override public void register(Colleague colleague) { if(!colleagues.contains(colleague)){ colleagues.add(colleague); colleague.setMediator(this); } } @Override public void relay(Colleague colleague) { for (Colleague col : colleagues) { if(!col.equals(colleague)){ col.receive(); } } } }
- 同事类
//同事抽象类 public abstract class Colleague{ protected Mediator mediator; public abstract void receive(); public abstract void send(); public void setMediator(Mediator mediator) { this.mediator = mediator; } } //A同事 public class AColleague extends Colleague{ @Override public void receive() { System.out.println("A接受请求"); } @Override public void send() { System.out.println("A发出请求"); mediator.relay(this); } } //B同事 public class BColleague extends Colleague{ @Override public void receive() { System.out.println("B接受请求"); } @Override public void send() { System.out.println("B发出请求"); mediator.relay(this); } }
- 测试
public static void main(String[] args) { Mediator mediator =new MediatorImpl(); AColleague aColleague = new AColleague(); BColleague bColleague = new BColleague(); //注册 mediator.register(aColleague); mediator.register(bColleague); //A发B接受 aColleague.send(); System.out.println("------------"); //B发A接受 bColleague.send(); }
网友评论