Java Design Pattern modeling and implementation of cainiao series (22) intermediary Pattern
Mediator: it is mainly used to reduce the coupling between classes, because if there is a dependency between classes, it is not conducive to function expansion and maintenance, because only one object needs to be modified, other associated objects must be modified.
I. uml modeling:
Ii. Code Implementation
/*** Mediator: it is mainly used to reduce coupling between classes, because if there is a dependency between classes, ** it is not conducive to function expansion and maintenance, because only one object needs to be modified, and other associated objects must be modified. ** Example: the following uses a house (rental) intermediary as an example */interface Mediator {void createMediator (); void recommendHouse () ;}/ *** (User) let the intermediary recommend the house for us ** so we need to hold an intermediary instance */abstract class User {private Mediator mediator; public User (Mediator mediator) {this. mediator = mediator;} public Mediator getMediator () {return mediator;} public abstract void selectHouse ();} class ZhangSan extends User {public ZhangSan (Mediator mediator) {super (mediator ); // TODO Auto-generated constructor stub} @ Overridepublic void selectHouse () {System. out. println (John is choosing a house ...);}} class LiSi extends User {public LiSi (Mediator mediator) {super (mediator); // TODO Auto-generated constructor stub} @ Overridepublic void selectHouse () {System. out. println (Li Si is choosing a house ...);}} /*** Housing Agency: the intermediary recommends a house to those who want to find the house and selects the house they want. ** Therefore, the intermediary must hold those instances to rent out the house. */Class MyMediator implements Mediator {private User zhangsan; private User lisi; public User getZhangsan () {return zhangsan;} public User getLisi () {return lisi ;} @ Overridepublic void createMediator () {zhangsan = new ZhangSan (this); lisi = new LiSi (this);}/*** the intermediary recommends the house to those who want to find the house, select the desired house */@ Overridepublic void recommendHouse () {zhangsan. selectHouse (); lisi. selectHouse () ;}}/*** client Test class ** @ author Leo */public class Test {public static void main (String [] args) {Mediator mediator = new MyMediator (); mediator. createMediator (); mediator. recommendHouse ();}}
Iii. Summary
The intermediary mode only needs to care about the relationship with the Mediator class. The relationship between the specific class and the call can be handed over to the Mediator class.