中介者模式

中介者模式就是在对象之间的关系很复杂时用,名如其人,就像租房的黑中介一样,如果每个房东都拿着很多租房者的信息很麻烦,每个租房者都要拿着很多房东的信息也麻烦,所以需要一个中介来拿着这些信息,租房者只需要发出租房的请求,中介会给你介绍合适的房东,房东只需要提交房屋资料就等着中介的人带着访客看房拿钱就行了,所以租房者和房东都要拿着中介的信息,这个模式不难理解,但是中介会用收中介费,加房租等毒辣手段,所以就是他来包装租房者发的请求,中间处理了一下交给房东,比如房租500,向租房者要1000,给房东400,呵呵。
Mediator 类可以增加很多租房者和房东间的交互。
 package com.jerry.design.mediator; //租房者 abstract class Colleague { private Mediator mediator; public Mediator getMediator() { return mediator; } public Colleague(Mediator m) { mediator = m; } // 租房者发送租房消息 public abstract void sendMsg(); // 房东接到看房的消息 public void getMsg() { System.out.println("Colleague1 要看房"); } } //租房者 class Colleague1 extends Colleague { public Colleague1(Mediator m) { super(m); } @Override public void sendMsg() { System.out.println("Colleague1 要看房"); getMediator().toFangdong(this); } @Override public void getMsg() { } } //租房者 class Colleague2 extends Colleague { public Colleague2(Mediator m) { super(m); } public void getMsg(String msg) { } public void sendMsg() { System.out.println("Colleague2 要看房"); } } //房东 class Colleague3 extends Colleague { public Colleague3(Mediator m) { super(m); } public void getMsg() { System.out.println("Colleague3房东接到了看房消息 "); } public void sendMsg() { System.out.println("Colleague3房东发出了提交资料给中介的消息 "); } } abstract class Mediator { public abstract void toFangdong(Colleague sender); } class ConcreteMediator extends Mediator { private Colleague1 colleague1; private Colleague2 colleague2; private Colleague3 colleague3; @Override public void toFangdong(Colleague sender) { if(sender!=colleague3){ colleague3.getMsg(); }else{ colleague3.sendMsg(); } } public Colleague1 getColleague1() { return colleague1; } public void setColleague1(Colleague1 colleague1) { this.colleague1 = colleague1; } public Colleague2 getColleague2() { return colleague2; } public void setColleague2(Colleague2 colleague2) { this.colleague2 = colleague2; } public Colleague3 getColleague3() { return colleague3; } public void setColleague3(Colleague3 colleague3) { this.colleague3 = colleague3; } } // 测试类 public class Test { public static void main(String[] args) { ConcreteMediator mediator = new ConcreteMediator(); Colleague1 colleague1 = new Colleague1(mediator); Colleague2 colleague2 = new Colleague2(mediator); Colleague3 colleague3 = new Colleague3(mediator); mediator.setColleague1(colleague1); mediator.setColleague2(colleague2); mediator.setColleague3(colleague3); mediator.toFangdong(colleague3); mediator.toFangdong(colleague1); mediator.toFangdong(colleague2); } } 
  

你可能感兴趣的:(中介者模式)