设计模式:中间人模式

中间人设计模式是用于协作一组同事。这些同事相互之间不直接沟通,而是通过中介。

在下面的例子中,同事A想要说话,同事B想要打架。当他们做动作(例如doSomething)的时候,他们调用中间人去做那些动作或事情。

1、中间人类图


设计模式:中间人模式2、代码实例

package com.leon.mediator;

interface IMediator {
	public void fight();

	public void talk();

	public void registerA(ColleagueA a);

	public void registerB(ColleagueB b);
}

//具体的中间人
class ConcreteMediator implements IMediator {

	ColleagueA a;
	ColleagueB b;

	@Override
	public void fight() {
		// TODO Auto-generated method stub
		System.out.println("中间人在打架!");
	}

	@Override
	public void talk() {
		// TODO Auto-generated method stub
		System.out.println("中间人在说话!");

	}

	@Override
	public void registerA(ColleagueA a) {
		// TODO Auto-generated method stub
		this.a = a;
	}

	@Override
	public void registerB(ColleagueB b) {
		// TODO Auto-generated method stub
		this.b = b;
	}

}

abstract class Colleague {
	IMediator mediator;

	public abstract void doSomething();
}

//同事A
class ColleagueA extends Colleague {

	public ColleagueA(IMediator mediator) {
		this.mediator = mediator;
		this.mediator.registerA(this);
	}

	@Override
	public void doSomething() {
		// TODO Auto-generated method stub
		this.mediator.talk();
	}

}

//同事B
class ColleagueB extends Colleague {

	public ColleagueB(IMediator mediator) {
		this.mediator = mediator;
		this.mediator.registerB(this);
	}

	@Override
	public void doSomething() {
		// TODO Auto-generated method stub
		this.mediator.fight();
	}

}

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

		ColleagueA talkColleague = new ColleagueA(mediator);
		ColleagueB fightColleague = new ColleagueB(mediator);

		talkColleague.doSomething();
		fightColleague.doSomething();
	}
}

 
 在其他行为类型的模式中,观察者模式跟中间人模式最为相似。你可以阅读下观察者模式来比较下两者的不同。

你可能感兴趣的:(java,设计模式)