设计模式之中介者模式

时间:2022-10-01 19:13:55

描述:中介者模式在我们日常生活中出现的频率比较多,例如现在市场上出现的房产中介,买家或者卖家都可以自己独立去找房子或者卖房子,还可以通过中介的方式去买房或者卖房,通过中介的方式买家和卖家必须把自己信息注册到中介Mediator中,当买家需要通过中介的方式买房时,买家先找到自己注册的中介,然后通过中介找到合适的卖家。


UML类图如下:

设计模式之中介者模式


测试代码如下:

1、中介抽象类

package com.java.mediator;

public abstract class Mediator {

protected ConcreteColleague1 colleague1;
protected ConcreteColleague2 colleague2;

public ConcreteColleague1 getColleague1() {
return colleague1;
}
public void setColleague1(ConcreteColleague1 colleague1) {
this.colleague1 = colleague1;
}
public ConcreteColleague2 getColleague2() {
return colleague2;
}
public void setColleague2(ConcreteColleague2 colleague2) {
this.colleague2 = colleague2;
}
public abstract void doSomething1();
public abstract void doSomething2();

}

2、具体中介

package com.java.mediator;

public class ConcreteMediator extends Mediator {

@Override
public void doSomething1() {
System.out.println("Colleague1 依赖别人做事情...");
}

@Override
public void doSomething2() {
System.out.println("Colleague2依赖别人 做事情...");
}

}


3、抽象Colleague

package com.java.mediator;

public abstract class Colleague {
protected Mediator mediator;

public Colleague(Mediator mediator) {
this.mediator = mediator;
}

}

4、具体Colleague

package com.java.mediator;

public abstract class Mediator {

protected ConcreteColleague1 colleague1;
protected ConcreteColleague2 colleague2;

public ConcreteColleague1 getColleague1() {
return colleague1;
}
public void setColleague1(ConcreteColleague1 colleague1) {
this.colleague1 = colleague1;
}
public ConcreteColleague2 getColleague2() {
return colleague2;
}
public void setColleague2(ConcreteColleague2 colleague2) {
this.colleague2 = colleague2;
}
public abstract void doSomething1();
public abstract void doSomething2();

}
package com.java.mediator;public class ConcreteColleague2 extends Colleague {	public ConcreteColleague2(Mediator mediator) {		super(mediator);	}		public void selfMethod(){		System.out.println("ConcreteColleague2独立做事情...");	}		public void depMethod(){		super.mediator.doSomething2();	}}

5、测试类

package com.java.mediator;

public class MediatorTest {

public static void main(String[] args) {
Mediator mediator = new ConcreteMediator();

ConcreteColleague1 c1 = new ConcreteColleague1(mediator);
ConcreteColleague2 c2 = new ConcreteColleague2(mediator);

c1.selfMethod();
c1.depMethod();
c2.selfMethod();
c2.depMethod();
}

}

6、测试结果

ConcreteColleague1独立做事情...
Colleague1 依赖别人做事情...
ConcreteColleague2独立做事情...
Colleague2依赖别人 做事情...