中介者模式是行为型模式的一种,在Mediator中,类之间的交互行为被统一放在Mediator对象中,对象通过Mediator对象同其他对象交互。
角色和职责:
1.中介者接口(Mediator):
中介者类的抽象父类
2.具体中介者(Concrete Mediator) -:
3.关联抽象父类(colleague)-:
关联类的抽象父类
4.具体关联类(concrete Mediator):
具体关联类
UML图:
具体代码:
/** * Colleague 抽象类 */public abstract class Person { private int condition;//条件,条件相同时,才匹配 private String name;//用户名 public Person(String name,int condition,ConcreteMediator mediator){ this.name = name; this.condition = condition; this.mediator = mediator; } protected ConcreteMediator mediator;//代理 public String getName() { return name; } public void setName(String name) { this.name = name; } public int getCondition() { return condition; } public void setCondition(int condition) { this.condition = condition; } abstract void getPartner(Person persion);//进行匹配}
/** * 男人 */public class Man extends Person{ public Man(String name, int condition,ConcreteMediator mediator) { super(name, condition, mediator); } @Override void getPartner(Person person) { this.mediator.setWoman(null);//初始化 this.mediator.setMan(this);//设置自己 this.mediator.contact(person);//去匹配 }}
/** * 女人 */public class Woman extends Person { public Woman(String name, int condition,ConcreteMediator mediator) { super(name, condition,mediator); } @Override void getPartner(Person person) { this.mediator.setMan(null);//初始化 this.mediator.setWoman(this);//设置自己 this.mediator.contact(person);//去匹配 }}
/** * 中介接口 */public interface Mediator { void contact(Person person);}
/** * 中介实现类 */public class ConcreteMediator implements Mediator{ private Man man;//男的 private Woman woman;//女的 @Override public void contact(Person person) { //中介中去匹配 if(person instanceof Man){ this.setMan((Man) person); }else if(person instanceof Woman){ this.setWoman((Woman) person); } //判断条件 if(man == null || woman == null){ System.out.println("我不是同性恋!"); }else if(man.getCondition() == woman.getCondition()){ System.out.println(man.getName() + "和" + woman.getName() + "绝配。"); }else{ System.out.println(man.getName() + "和" + woman.getName() + "不配"); } } public Man getMan() { return man; } public void setMan(Man man) { this.man = man; } public Woman getWoman() { return woman; } public void setWoman(Woman woman) { this.woman = woman; }}
public class Main { public static void main(String[] args) { ConcreteMediator concreteMediator = new ConcreteMediator(); Person zhangsan = new Man("张三",3,concreteMediator); Person xiaohong = new Woman("小红",2,concreteMediator); Person lisi = new Man("李四",2,concreteMediator); zhangsan.getPartner(xiaohong);//查看是否相配 zhangsan.getPartner(lisi);//查看是否相配 lisi.getPartner(xiaohong);//查看是否相配 }}
结果:
张三和小红不配
我不是同性恋!李四和小红绝配。
源码地址::https://github.com/qjm201000/design_pattern_mediator.git