Mediator模式

用一个中介对象来封装一系列的对象交互,使各对象不需要显示地相互调用

 


Mediator模式_第1张图片
 

Mediator.java

package com.gary.designpattern.mediator;

/**
 * 中介者
 * @author gary
 *
 */
public interface Mediator {
	public void send(String message, Person person);
}

 

MediatorImpl.java

package com.gary.designpattern.mediator;

public class MediatorImpl implements Mediator {
	//中介者需要知道所有具体对象
	private PersonA personA;
	private PersonB personB;
	
	public void setPersonA(PersonA personA) {
		this.personA = personA;
	}
	
	public void setPersonB(PersonB personB) {
		this.personB = personB;
	}
	
	@Override
	public void send(String message, Person person) {
		if(person.equals(personA)){
			personA.greeting(message);
		}else{
			personB.greeting(message);
		}
	}


}

 

Person.java

package com.gary.designpattern.mediator;

public abstract class Person {
	protected Mediator mediator;

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

 

PersonA.java

package com.gary.designpattern.mediator;

public class PersonA extends Person {

	public PersonA(Mediator mediator) {
		super(mediator);
	}
	
	/**
	 * 通过中介者发送信息
	 * @param message
	 */
	public void send(String message){
		mediator.send(message, this);
	}
	
	public void greeting(String message){
		System.out.println("PersonA: " + message);
	}
}

 

PersonB.java

package com.gary.designpattern.mediator;

public class PersonB extends Person {

	public PersonB(Mediator mediator) {
		super(mediator);
	}
	
	/**
	 * 通过中介者发送信息
	 * @param message
	 */
	public void send(String message){
		mediator.send(message, this);
	}
	
	public void greeting(String message){
		System.out.println("PersonB: " + message);
	}
}

 

Test.java

package com.gary.designpattern.mediator;

/**
 * 测试
 * @author gary
 *
 */
public class Test {
	public static void main(String[] args) {
		MediatorImpl ci = new MediatorImpl();
		//让具体对象认识中介者
		PersonA personA = new PersonA(ci);
		PersonB personB = new PersonB(ci);
		//让中介者认识具体对象
		ci.setPersonA(personA);
		ci.setPersonB(personB);
		
		//通过中介者转发
		personA.send("Hello B!");
		personB.send("Hi A!");
	}
}

 

你可能感兴趣的:(java)