中介者模式(Mediator Pattern)
用一个中介对象来封装一系列对象之间的交互,使各个对象不需要显式地引用其他对象实例,从而降低各个对象之间的耦合度,并且可以独立地改变对象间的交互关系。
举例:多人聊天,一个人发消息,其他人都能收到(服务器相当于中介者)
抽象用户类
public abstract class AbstractUser{
private IMediator mediator;
private String name;
public AbstractUser(String name,IMediator mediator){
this.name=name;
this.mediator=mediator;
}
public String getName() {
return name;
}
public void receiveMessage(String msg){
System.out.println(this.name+"收到消息:"+msg);
}
public void sendMessage(String msg){
System.out.println(this.name+"说:"+msg);
mediator.notifyAllUser(this,msg);
}
}
中介者接口
public interface IMediator {
/**
* description 注册用户
* @param user
*/
public void register(AbstractUser user);
/**
* description 消息广播
* @param sendUser
*/
public void notifyAllUser(AbstractUser sendUser,String msg);
}
实际中介者类
public class Mediator implements IMediator{
private ArrayList<AbstractUser> userList=new ArrayList<AbstractUser>();
@Override
public void register(AbstractUser user) {
if(user!=null&&!userList.contains(user)){
userList.add(user);
}
}
@Override
public void notifyAllUser(AbstractUser sendUser,String msg) {
for(AbstractUser user:userList){
if(!user.equals(sendUser)){
user.receiveMessage(msg);
}
}
}
}
三个用户类
public class UserA extends AbstractUser{
public UserA(String name, IMediator mediator) {
super(name, mediator);
mediator.register(this);
}
}
public class UserB extends AbstractUser{
public UserB(String name, IMediator mediator) {
super(name, mediator);
mediator.register(this);
}
}
public class UserC extends AbstractUser{
public UserC(String name, IMediator mediator) {
super(name, mediator);
mediator.register(this);
}
}
测试类
public class Demo {
public static void main(String[] args) {
IMediator mediator=new Mediator();
UserA a=new UserA("a", mediator);
UserB b=new UserB("b", mediator);
UserC c=new UserC("c", mediator);
a.sendMessage("大家好!");
System.out.println("---------");
b.sendMessage("大家辛苦了!");
System.out.println("---------");
c.sendMessage("为人民服务!");
}
}
测试结果
a说:大家好!
b收到消息:大家好!
c收到消息:大家好!
---------
b说:大家辛苦了!
a收到消息:大家辛苦了!
c收到消息:大家辛苦了!
---------
c说:为人民服务!
a收到消息:为人民服务!
b收到消息:为人民服务!