"Onlookers" design pattern (25)--Behavioral type of Mediator mode (mediator pattern)

Source: Internet
Author: User

Encapsulating a series of object interactions with an object, the mediator makes the object do not need to display the interaction, so that it is loosely coupled, and can independently change their independence.


Personal Understanding

When there is too much coupling between multiple objects, it can be decoupled by the mediator mode, and the coupling between the concrete objects is transferred to the coupling between the mediator and the concrete object, if the former is the coupling between the three objects and the coupling between the intermediary and the concrete class, the coupling is greatly reduced, If it is modified again, then the change is mainly in the intermediary part, which makes the structure more stable.


Role Analysis

The mediator role is divided into the following sections:

1. Mediator Abstract Mediator role: The abstract mediator role defines a unified interface for communication between colleague roles.

2. Concrete mediator specific Mediator role: the role of specific intermediaries to achieve writing by coordinating the roles of colleagues, relying on the role of each colleague.

3. Colleague co-worker role: Each colleague class of tasks, including their own needs to complete the function, and do not have to hand over to the intermediary to do the rest of the processing of some of the functions.


Case Analysis


Case One: The application of the intermediary mode of purchase and sale system
Case Background Introduction

By the company's purchase and sale system, when the purchase of goods, inventory needs to be correspondingly increased, here is dependent on other objects of the relationship. Need to clearance, on the one hand, need to stop the purchase, discount sales to complete the clearance task. From these parts of the entity class (Purchase, Sale, Store) If you do not use the intermediary mode, you need to complete the purchase of the task, so that the Purchase class depends on the Store class. The store relies on the purchase class and the sale class when completing tasks such as clearance and promotion. Such dependencies are overly complex and not easy to manage.

With the mediator pattern, the dependencies between the three are pure and simple, coupled only with the mediator class, and the rest can be done in the Mediator class. This facilitates both management and maintenance, as well as reduced coupling for improved stability.


Main code

Equivalent to a colleague role abstract class. Defines common properties and constructs a method.

Public abstract class Abstractemployee {protected Abstractmediator mediator;public Abstractemployee () {}public Abstractemployee (Abstractmediator mediator) {this.mediator = mediator;}}
specific colleague Role implementation class
public class Purchaseman extends Abstractemployee {public Purchaseman () {}public Purchaseman (abstractmediator mediator) {Super (mediator);} public void Buy (int i) {this.mediator.executor ("buy", I);} public void Stopbuy () {System.out.println ("Stop Purchase");}}

public class Saleman extends Abstractemployee {public Saleman () {}public Saleman (Abstractmediator mediator) {super ( Mediator);} public int GetStatus () {Random random = new random (); int num = random.nextint; return num;} public void sale (Integer num) {this.mediator.executor ("sale", num);}}

public class Storeman extends Abstractemployee {private int num = 100;public storeman () {}public storeman (abstractmediator Mediator) {super (mediator);} public void Increasestore (Integer num) {this.num + = num;} Public Integer Getnum () {return this.num;} public void Clearstore () {this.mediator.executor ("sell", This.num);} public void Decreasestore (Integer num2) {this.num-= num2;}}

Mediator role Abstract class: The abstract Mediator role defines a unified interface for communication between colleague roles.

Public abstract class Abstractmediator {protected static Purchaseman purchase = new Purchaseman ();p rotected static Saleman Sale = new Saleman ();p rotected static Storeman store = new Storeman ();p ublic abstract void Executor (String exestr, Object .... obj);}
concrete Mediator specific mediator role: the role of the specific mediator in coordinating the roles of colleagues to achieve writing behavior, relying on the role of colleagues.

public class Mediator extends Abstractmediator {@Overridepublic void executor (String exestr, Object ... obj) {//Purchase if ("buy" . Equals (Exestr)) {this.buysomething ((Integer) obj[0]);} Sell else if ("sell". Equals (Exestr)) {this.sellsomething ((Integer) obj[0]);} Clearance else if ("clear". Equals (Exestr)) {this.clear ();} Discount Promotions Else if ("Sale". Equals (Exestr)) {This.sale ((Integer) obj[0]);}} private void sale (int num) {System.out.println ("cheap sell" + num);} private void Clear () {System.out.println ("Clear---start"), if (Store.getnum () > 0) {System.out.println ("Clearance >>" + Store.getnum ());p urchase.stopbuy (); Sale.sale (Store.getnum ()); Store.decreasestore (Store.getnum ());} else {System.out.println ("already clearance");} SYSTEM.OUT.PRINTLN ("Clear---stop");} private void sellsomething (Integer num) {System.out.println ("sell----start"), if (Store.getnum () <= num) { System.out.println ("buy" + (Num-store.getnum ())); SYSTEM.OUT.PRINTLN ("clearance");p Urchase.buy (Num-store.getnum ()); Store.clearstore ();} else {System.out.println ("sell" + num); sTore.decreasestore (num);} SYSTEM.OUT.PRINTLN ("sell----End");} private void buysomething (Integer num) {System.out.println ("buy----start"); if (Sale.getstatus () > 100) { System.out.println ("buy-in" + num); Store.increasestore (num);} Else{system.out.println ("buy-in" + NUM/3); Store.increasestore (NUM/3);} System.out.println ("buy----End");}}

Test Class

public class Maintest {public static void main (string[] args) {Mediator mediator = new Mediator (); Purchaseman purchase = new Purchaseman (mediator);p urchase.buy (100); Saleman sale = new Saleman (mediator); Sale.sale (100); Storeman store = new Storeman (mediator); Store.clearstore ();}}

case two: simulating airport dispatch


Case Background

It is important for the airfield to be used as an intermediary for the landing of each aircraft, and if an aircraft is landing on the current runway, the other aircraft reached will not be able to land, and the aircraft will have to wait until the aircraft has landed and the plane arrives safely. This example uses the multi-threaded way to carry on the intermediary pattern. Simulate the landing process of the aircraft.


Main code

An abstract class equivalent to a colleague class. Defines the intermediaries and some of the necessary methods for landing aircraft.

Public abstract class Airplane {protected static ariportmediator mediator = new Ariportmediator ();/** * ready to land */public Abst Ract  void preparelanded ();/** * Check for Security */public abstract Boolean checkissafe ();/** * Landing */public abstract void landing /** * Continue to fly until security is confirmed */public abstract void Continuetofly ();p ublic void Landingmethod () {this.preparelanded (); if ( This.checkissafe ()) {Landing ();} Else{continuetofly ();}}}

public class Cnairplane extends airplane{@Overridepublic void preparelanded () {System.out.println ("cnairplane--ready to land!) "); this.mediator.setAirPlaneWaitingLoading (this);} @Overridepublic synchronized Boolean checkissafe () {return This.mediator.checkIsSafe ();} @Overridepublic synchronized void Landing () {this.mediator.setStatus (0); System.out.println ("cnairplane--is landing! "), try {new Thread (). Sleep (2000);} catch (Exception e) {e.printstacktrace ();} This.mediator.removeAirplane (this); System.out.println ("cnairplane--Landing done! "); This.mediator.setStatus (1);} @Overridepublic void Continuetofly () {System.out.println ("cnairplane--continue to fly! "); (true) {if (This.mediator.checkIsSafe ()) {Landing (); break;}}}

public class Cnshairplane extends airplane{@Overridepublic void preparelanded () {System.out.println (" cnshairplane--Ready to land! "); this.mediator.setAirPlaneWaitingLoading (this);} @Overridepublic Boolean Checkissafe () {return This.mediator.checkIsSafe ();} @Overridepublic synchronized void Landing () {System.out.println ("cnshairplane--is landing! "), try {new Thread (). Sleep (1000);} catch (Exception e) {e.printstacktrace ();} This.mediator.setStatus (0); This.mediator.removeAirplane (this); System.out.println ("cnshairplane--Landing done! ");} @Overridepublic void Continuetofly () {System.out.println ("cnshairplane--continue to fly! "); (true) {if (This.mediator.checkIsSafe ()) {Landing (); break;}}}
Mediator role, complete the interaction of multiple aircraft roles, and coordinate the landing relationship, so that the aircraft can be safely landed.
public class Ariportmediator {//Record aircraft application for landing sequence private static list<object> airplanewaitingloading = new arraylist< Object> ();//aircraft Landing State 0: Indicates that no landing is possible, and 1 indicates that it is possible to land. private static int airplaneloadingstatus = 1;public static list<object> getairplanewaitingloading () {return airplanewaitingloading;} public static synchronized void setairplanewaitingloading (Object airplane) {airplanewaitingloading.add (airplane);// System.out.println (airplanewaitingloading);} public static synchronized void Removeairplane (Object airplane) {airplanewaitingloading.remove (airplane);// System.out.println (airplanewaitingloading);} Public synchronized Boolean Checkissafe () {//aircraft preparing to land if (airplanewaitingloading! = null && Airplanewaitingloading.size () > 1 | | Airplaneloadingstatus = = 0) {return false;} Else{return true;}} Public synchronized void setStatus (int status) {Airplaneloadingstatus = status;//System.out.println ("state:" + Airplaneloadingstatus);} public int GetStatus () {return airplaneloadingstatus;}}

Test Class

public class Maintest {public static void main (string[] args) {new Thread (new Runnable () {@Overridepublic void run () {AIRP Lane airplane = new Cnairplane (); Airplane.landingmethod ();}}). Start (); New Thread (New Runnable () {@Overridepublic void run () {Airplane airPlane2 = new Cnshairplane (); Airplane2.landingmethod ();}}). Start ();}}


Broker Mode Benefits

Reduce dependencies between classes, turn the original one-to-many dependencies into one-to-one dependencies, reduce dependence, reduce coupling, and improve stability.


Broker Mode Disadvantage

Causes the intermediary class expands, the logic is too complex, the colleague class is more, then the intermediary logic is more complicated.


design mode code Download

Design mode source code download




"Onlookers" design pattern (25)--Behavioral type of Mediator mode (mediator pattern)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.