一、中介者模式:用一个中介对象来封装一系列的对象交互。中介者使各对象不需要显示的相互引用,从而使其耦合松散,而且可以独立地改变它们之间的交互。
二、代码示例
public interface UnitedNations { void declare(String message, Country country); } public abstract class Country { protected UnitedNations mediator; public Country(UnitedNations mediator) { this.mediator = mediator; } } public class Iraq extends Country { public Iraq(UnitedNations mediator) { super(mediator); } public void declare(String message){ mediator.declare(message,this); } public void getMessage(String message){ System.out.println("伊拉克获得对方信息:" + message); } } public class USA extends Country { public USA(UnitedNations mediator) { super(mediator); } public void declare(String message){ mediator.declare(message,this); } public void getMessage(String message){ System.out.println("美国获得对方信息:" + message); } } @Data public class UnitedNationsSecurityCouncil implements UnitedNations { private USA usa; private Iraq iraq; @Override public void declare(String message, Country country) { if(country instanceof USA){ iraq.getMessage(message); }else if(country instanceof Iraq){ usa.getMessage(message); }else { System.out.println("没有国家接到消息:" + message); } } } public class Main { public static void main(String[] args) { UnitedNationsSecurityCouncil securityCouncil = new UnitedNationsSecurityCouncil(); USA usa = new USA(securityCouncil); Iraq iraq = new Iraq(securityCouncil); securityCouncil.setIraq(iraq); securityCouncil.setUsa(usa); usa.declare("不准研制核武器,否则发动战争"); iraq.declare("我们没有核武器,也不怕侵略"); } }
三、优缺点
优点:减少耦合,可得可以独立的改变和复用Colleague类和Mediator类。
缺点:中介者实现类会过于复杂。