1.定义
Mediator模式也叫中介者模式,是由GOF提出的23种软件设计模式中的一种。Mediator模式是行为模式之一,在Mediator模式中,类之间的交互行为被统一放在Mediator的对象中,对象通过Mediator对象同其他对象交互,Mediator对象起着控制器的作用。
2.中介者模式的结构
3.中介者模式的角色和职责
mediator--中介者类的抽象父类
concreteMediator--具体的中介者类
colleague--关联类的抽象父类
concreteColleague--具体的关联类
4.中介者模式的优点
- 将系统按功能分割成更小的对象,符合类的最小设计原则。
- 对关联对象的集中控制。
- 减小类的耦合程度,明确类之间的相互关系:当类之间的关系过于复杂时,其中任何一个类的修改都会影响到其他类,不符合类的设计的开闭原则,而Mediator模式将原来相互依存的多对多的类之间的关系简化为Mediator控制类与其他关联类的一对多的关系,当其中一个类修改时,可以对其他关联类不产生影响(即使有修改,也集中在Mediator控制类)。
- 有利于提高类的重用性。
5.代码演示
package test.com.mediator2; /* * colleague--关联类的抽象父类 */ public abstract class Person { private String name; private int condition; private Mediator mediator; public Person(String name, int condition, Mediator mediator) { this.name = name; this.condition = condition; this.mediator = mediator; } public Mediator getMediator() { return mediator; } public void setMediator(Mediator mediator) { this.mediator = 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; } public abstract void getPartner(Person person); }
package test.com.mediator2; /* * concreteColleague--具体的关联类 */ public class Man extends Person { public Man(String name, int condition, Mediator mediator) { super(name, condition, mediator); } @Override public void getPartner(Person person) { this.getMediator().setMan(this); this.getMediator().getPartner(person); } }
package test.com.mediator2; /* * concreteColleague--具体的关联类 */ public class Woman extends Person { public Woman(String name, int condition, Mediator mediator) { super(name, condition, mediator); } @Override public void getPartner(Person person) { this.getMediator().setWoman(this); this.getMediator().getPartner(person); } }
package test.com.mediator2; /* * concreteMediator--具体的中介者类 */ public class Mediator { private Man man; private Woman woman; 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 void getPartner(Person person) { if(person instanceof Man) { this.setMan((Man)person); } else if(person instanceof Woman) { this.setWoman((Woman)person); } if(this.man == null || this.woman == null) { System.out.println("我不是同性恋!"); } else { if(this.man.getCondition() == this.woman.getCondition()) { System.out.println(this.man.getName() + "和" + this.woman.getName() + "是绝配"); } else { System.out.println(this.man.getName() + "和" + this.woman.getName() + "不相配"); } } } }
package test.com.mediator2; /* * 测试 */ public class MainClass { public static void main(String[] args) { Mediator mediator = new Mediator(); Person man = new Man("李强", 2, mediator); Person man2 = new Man("卫凯强", 1, mediator); Person woman = new Woman("史芳娟", 2, mediator); man.getPartner(man2); man.getPartner(woman); man2.getPartner(woman); } }