概念:
中介者模式:Define an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently. 定义一个对象封装一些对象的交互。中介者使各对象不需要显示的相互作用,从而使其耦合松散,而且可以独立的改变与他们之间的交互。
实现:
定义中介者接口
public interface MarriageAgency { void pair(AbstractPerson person); void register(AbstractPerson person); }
抽象实体类
public abstract class AbstractPerson { private String name; private Integer age; private Sex sex; private Integer requestAge; private MarriageAgency agency; public AbstractPerson(String name, Integer age, Sex sex, Integer requestAge, MarriageAgency agency) { this.name = name; this.age = age; this.sex = sex; this.requestAge = requestAge; this.agency = agency; agency.register(this); } public void findPartner() { agency.pair(this); } //add getter and setter... }
中介者实现
public class MarriageAgencyImpl implements MarriageAgency { private List<Man> manList = new ArrayList<>(); private List<Woman> womenList = new ArrayList<>(); @Override public void pair(AbstractPerson person) { if (person.getSex().equals(Sex.MALE)) { match(womenList, person); } else if (person.getSex() == Sex.FEMALE) { match(manList, person); } } private <T extends AbstractPerson> void match(List<T> list, AbstractPerson person) { for (AbstractPerson item : list) { if (person.getRequestAge().equals(item.getAge())) { System.out.println(person.getName() + "和" + item.getName() + "匹配成功"); return; } } /* * 这里如果使用lambda表达式,return不能结束该方法返回,只能结束lambda表达式所在的forEach循环 */ // list.forEach(item->{ // if(person.getRequestAge().equals(item.getAge())){ // System.out.println(person.getName()+"和"+item.getName()+"匹配成功"); // return; // } // }); System.out.println(person.getName() + "没有匹配到"); } @Override public void register(AbstractPerson person) { if (person.getSex() == Sex.MALE) { manList.add((Man) person); } else if (person.getSex().equals(Sex.FEMALE)) { womenList.add((Woman) person); } } }
具体类实现
public class Man extends AbstractPerson { public Man(String name, Integer age, Sex sex, Integer requestAge, MarriageAgency agency) { super(name, age, sex, requestAge, agency); } }
public class Woman extends AbstractPerson { public Woman(String name, Integer age, Sex sex, Integer requestAge, MarriageAgency agency) { super(name, age, sex, requestAge, agency); } }
public enum Sex { MALE,FEMALE }
测试及结果:
@Test public void mediatorTest(){ MarriageAgency agency = new MarriageAgencyImpl(); AbstractPerson person1 = new Man("张一",24, Sex.MALE,22,agency); AbstractPerson person2 = new Woman("张二",23, Sex.FEMALE,22,agency); AbstractPerson person3 = new Woman("张三",22, Sex.FEMALE,22,agency); AbstractPerson person4 = new Woman("张四",21, Sex.FEMALE,22,agency); person1.findPartner(); person2.findPartner(); person3.findPartner(); person4.findPartner(); }
张一和张三匹配成功
张二没有匹配到
张三没有匹配到
张四没有匹配到
分析:
1.虽然增加了中介者,但降低了具体实现类的复杂度,整体来说是有利与代码的维护。
2.中介者模式容易被误用或者滥用,因为各中介者的处理逻辑不相同,导致代码不能有效复用。
3.中介者模式存在的意义在于简化依赖关系,通常能将一对多依赖转换成一对一依赖。