One
Broker Mode (mediator)
The mediator pattern is also used to reduce the coupling between class classes, because if there is a dependency between class classes, it is not conducive to the expansion and maintenance of functions, because as long as you modify an object, the other associated objects will have to be modified. If you use the mediator mode, just care about the relationship with the Mediator class, the relationship between the specific class classes and scheduling to mediator on the line, which is a bit like the role of spring container. First look at the picture:
User Class Unified interface, User1 and User2 are different objects, there is a correlation between the two, if you do not use the intermediary mode, you need to hold a reference to each other, so that the coupling is very high, for the understanding of decoupling, introduced the Mediator class, provides a unified interface, Mymediator for its implementation class, which holds User1 and User2 instances, used to achieve User1 and User2 control. So User1 and User2 two objects are independent of each other, they just need to keep good and mediator relationship between the line, the rest of all by the Mymediator class to maintain! Basic implementation:
- Public interface Mediator {
- public void Createmediator ();
- public void Workall ();
- }
- Public class Mymediator implements mediator {
- Private User user1;
- Private User User2;
- Public User GetUser1 () {
- return user1;
- }
- Public User GetUser2 () {
- return user2;
- }
- @Override
- public void Createmediator () {
- User1 = new User1 (this);
- User2 = new User2 (this);
- }
- @Override
- public void Workall () {
- User1.work ();
- User2.work ();
- }
- }
- Public abstract class User {
- Private mediator mediator;
- Public Mediator Getmediator () {
- return mediator;
- }
- Public User (mediator mediator) {
- This.mediator = Mediator;
- }
- public abstract void work ();
- }
- public class User1 extends User {
- Public User1 (mediator mediator) {
- Super (mediator);
- }
- @Override
- public void work () {
- System.out.println ("User1 exe!");
- }
- }
- public class User2 extends User {
- Public User2 (mediator mediator) {
- Super (mediator);
- }
- @Override
- public void work () {
- System.out.println ("User2 exe!");
- }
- }
Test class:
- public class Test {
- public static void Main (string[] args) {
- Mediator Mediator = new Mymediator ();
- Mediator.createmediator ();
- Mediator.workall ();
- }
- }
Output:
User1 exe!
User2 exe!
Reprinted from Https://www.cnblogs.com/maowang1991/archive/2013/04/15/3023236.html
------Broker Pattern for Java 23 design Patterns