中介者模式

中介者模式(Mediator Pattern):定义一个中介对象来封装系列对象之间的交互。中介者使各个对象不需要显示地相互引用,从而使其耦合性松散,而且可以独立地改变他们之间的交互。

package mode.mediator;

import java.util.Hashtable;

public abstract class AbstractMediator {
	//定义一个哈希表来存放同事类
	protected Hashtable<String, AbstractColleague> colleagues = new Hashtable<String, AbstractColleague>();

	//添加同事到同事类的哈希表中
	public void addColleague(String name, AbstractColleague colleague) {
		//在这里将我们的中介者反向注册到同事类中去
		colleague.setMediator(this);
		//添加一个同事对象
		this.colleagues.put(name, colleague);
	}

	//移除一个同事对象
	public void deleteColleague(String name) {
		this.colleagues.remove(name);
	}

	//用来负责各同事之间的交互,name代表同事的名称,method代表要执行的操作
	public abstract void execute(String name, String method);
}


package mode.mediator;

public abstract class AbstractColleague {
	//保存中介者
	protected AbstractMediator mediator;

	public void setMediator(AbstractMediator mediator) {
		this.mediator = mediator;
	}

	//自己要做的事情
	public abstract void self();
	//请求他人完成的事情
	public abstract void out();
}


package mode.mediator;

/**
 * 
 * 实现一个具体的中介类,用来负责个同事之间的交流
 * 
 * */
public class Mediator extends AbstractMediator {

	@Override
	//根据发来的请求调用不同的方法
	public void execute(String name, String method) {
		if (method.equals("self")) {
			AbstractColleague colleague = (AbstractColleague) colleagues
					.get(name);
			colleague.self();
		} else {
			AbstractColleague colleague = (AbstractColleague) colleagues
					.get(name);
			colleague.out();
		}
	}

}


两个同事类的实现类

package mode.mediator;

public class ColleagueA extends AbstractColleague {

	@Override
	public void self() {
		System.out.println("同事A--》完成了自己的工作");

	}

	@Override
	public void out() {
		System.out.println("同事A--》请求同事B做好分内工作");
		mediator.execute("ColleagueB", "self");
	}

}


package mode.mediator;

public class ColleagueB extends AbstractColleague {

	@Override
	public void self() {
		System.out.println("同事B做好自己的工作");
	}

	@Override
	public void out() {
		System.out.println("同事B请求同事A做好自己的分内工作");
		mediator.execute("ColleagueA", "self");
	}

}


测试


package mode.mediator;

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

		ColleagueA colleagueA = new ColleagueA();
		ColleagueB colleagueB = new ColleagueB();

		mediator.addColleague(colleagueA.getClass().getSimpleName(), colleagueA);
		mediator.addColleague(colleagueB.getClass().getSimpleName(), colleagueB);

		colleagueA.self();
		colleagueA.out();

		System.out
				.println("-----------------------------------------------------------");

		colleagueB.self();
		colleagueB.out();
	}
}


posted @ 2015-03-11 13:02  qz程程  阅读(114)  评论(0编辑  收藏  举报