本文最后更新于 2025年7月27日 中午
用一个中介对象来封装一系列的对象交互。中介者模式使各对象不需要显式的相互引用,从而使其耦合松散,而且可以独立地改变它们之间的交互。
角色
- 抽象中介者 : 抽象中介者角色定义统一的接口,以及一个或者多个事件方法,用于各同事角色之间的通信
- 具体中介者 : 实现了抽象中介者所声明的事件方法,协调各同事类之间的行为,持有所有同事类对象的引用。
- 抽象同事类 :定义了抽象同事类,持有抽象中介者对象的引用
- 具体同事类 :继承抽象同事类,实现自己的业务通过中介者跟其他同事类进行通信
场景
- 系统中的对象间存在较为复杂的引用,导致依赖关系和结构混乱而无法复用的情况
- 想通过一个中间类来封装多个类的行为,但是又不想要太多的子类
优点
- 松散耦合将多个对象之间的联系紧耦合封装到中介对象中,做到松耦合,不会导致牵一发而动全身
- 将多个对象之间的交互联系集中在中介对象中,发生变化时,仅需修改中介对象即可,提供系统的灵活性,使同事对象对立而易于复用
- 符合迪米特原则,一个对象应当对其他对象有尽可能少的了解
缺点
当各个同事间的交互非常多且非常复杂时,如果都交给中介者处理,会导致中介者变得十分复杂。
实现中介者模式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
| public interface PostOffice { void deliverLetter(String letter , String receiver);
void addPeople(People people);
}
public class PostOfficeImpl implements PostOffice{ private Map<String , People>peopleMap = new HashMap<>();
@Override public void deliverLetter(String letter , String receiver){ System.out.println("=>收信"); People people = peopleMap.get(receiver); System.out.println("=>送信"); System.out.println("=>收信人看信"); people.receiveLetter(letter); }
@Override public void addPeople(People people){ peopleMap.put(people.getClass().getSimpleName(),people); } }
public abstract class People{ protected PostOffice postOffice; public String getAddress(){ return address ; } public void receiveLetter(String letter){ System.out.println(letter); } public void sendLetter(String letter,String receiver){ postOffice.deliverLetter(letter,receiver); } public void setAddress(String address){ this.address = address ; } private String address ; public People(PostOffice postOffice , String address){ this.postOffice = postOffice; this.address = address ; } }
public class People1 extends People{ public People1(PostOffice postOffice, String address){ super(postOffice , address); } }
public class People2 extends People{ public People2(PostOffice postOffice , String address){ super(postOffice , address); } }
public class Client{ public static void main(String[] args){ PostOffice postOffice = new PostOfficeImpl();
}
}
|
总结
中介者模式通过引入一个中介对象将多个对象之间的复杂依赖转化为“一对多”的依赖关系,避免了“网状”结构演变为“星型”结构。这样不仅降低了类与类之间的耦合性,还提升了对象之间协作的灵活性和系统的可维护性。