Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Messing with the intermediary pattern of Java design pattern

2025-01-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/03 Report--

The original site of the blog post: the intermediary pattern of messing with the Java design pattern

Intermediary model

The intermediary pattern (Mediator Pattern) is used to reduce the complexity of communication between multiple objects and classes. This pattern provides a mediation class that usually handles communication between different classes and supports loose coupling, making the code easy to maintain. The intermediary model belongs to the behavioral model.

Popular point is to provide an intermediary platform, when it comes to the platform, it is actually very easy to contact the real estate agents we are very familiar with. We can get the information we want directly through this platform without the object itself interacting with other objects.

If you buy a house and rent a house, you don't need to go to the landlord, just get the corresponding information from the intermediary. As shown in the figure below, both parties only need to find an intermediary.

Cdn.xitu.io/2019/4/11/16a09f7d3a72b202?w=500&h=391&f=jpeg&s=22358 ">

Let's take a look at another comparison picture.

Do you feel that before use, objects depend on each other and call each other, intricate and intertwined? when you join the intermediary, the relationship between objects is clear at a glance. The interaction between a series of objects is encapsulated by mediation objects. Intermediaries make it unnecessary for objects to refer to each other explicitly, so that the coupling is reduced, and the interaction between them can be changed independently.

Intermediary Mode UML Diagram UML Class Diagram and sequence Diagram

The collague1 and collague2 classes are not directly dependent on each other; they are common mediation interfaces (mediate () methods) that control and coordinate interactions, which gives them a way to interact independently. The mediate1 class implements the dependency between collague1 and collague2.

Intermediary model role

Abstract intermediary (Mediator): defines the interface between colleague objects and intermediary objects.

Concrete intermediary (ConcreteMediator): a method that implements an abstract intermediary, which needs to know all the concrete colleague classes, receive information from the concrete colleague class, and send information to the concrete colleague class.

Abstract colleague class (Colleague): defines the interface of the mediator object, which only knows the mediator and not the other colleague objects.

Specific colleague class (ConcreteColleague): each specific colleague class only needs to know its own behavior, but they all need to know the intermediary.

Sample code

Source code address

Abstract intermediary

@ Slf4jpublic abstract class Mediator {/ * * landlord map * / protected Map landlordMap = Maps.newHashMap (); / * tenant list * / protected List renterList = Lists.newArrayList () / * registered landlord information * * @ param landlord landlord * @ param message housing information * / public void registerLandlord (People landlord, Message message) {landlordMap.put (landlord, message); log.info ("intermediary information: landlord | {} | join the intermediary platform, housing information: {}", landlord.getName (), message) } / * change landlord information * * @ param landlord landlord * @ param message housing information * / protected void modifyLandlordInfo (People landlord, Message message) {landlordMap.put (landlord, message); log.info ("intermediary information: landlord | {} | modify his housing information on the intermediary platform, current housing information: {}", landlord.getName (), message) } / * registered tenant information * * @ param renter tenant * / public void registerRenter (People renter) {renterList.add (renter); log.info ("intermediary information: tenant | {} | come to the intermediary platform to rent a house", renter.getName ()) } / * declares that abstract methods are transferred and coordinated by concrete mediator subclasses * / public abstract void operation (People people, Message message);}

Abstract colleague class

@ Data@AllArgsConstructor@NoArgsConstructorpublic abstract class People {private Mediator mediator; private String name; / * send message * / protected abstract void sendMessage (Message message) to mediation; / * get message from mediation * / protected abstract void getMessage (Message message);}

Landlords and tenants of specific colleagues

@ Slf4jpublic class Landlord extends People {public Landlord (Mediator mediator, String name) {super (mediator, name);} @ Override protected void sendMessage (Message message) {getMediator (). Operation (this, message);} @ Override protected void getMessage (Message message) {log.info ("landlord | {} | Information obtained from intermediary to tenant: {}", getName (), message) } @ Slf4jpublic class Renter extends People {public Renter (Mediator mediator, String name) {super (mediator, name);} @ Override protected void sendMessage (Message message) {getMediator (). Operation (this, message);} @ Override protected void getMessage (Message message) {log.info ("tenant | {} | Information obtained from the intermediary to the landlord: {}", getName (), message);}}

Specific intermediary

Public class RealEstateAgent extends Mediator {@ Override public void operation (People people, Message message) {if (people instanceof Renter) {/ / send the tenant's rental condition information to the landlords landlordMap.keySet () .forEach (landlord-> landlord.getMessage (message)) / / the tenant receives the landlord's housing information landlordMap.values (). ForEach (messages-> people.getMessage (messages));} else if (people instanceof Landlord) {/ / sends the landlord's housing information to the tenants renterList.forEach (renter-> renter.getMessage (message)) / / change the landlord housing information in the intermediary modifyLandlordInfo (people, message);}

Client

@ Slf4jpublic class Client {public static void main (String [] args) {Mediator mediator = new RealEstateAgent (); People laoWang = new Landlord (mediator, "Lao Wang"); People laoLee = new Landlord (mediator, "Lao Li"); People laoBai = new Landlord (mediator, "Lao Bai"); People xiaoSan = new Renter (mediator, "Xiao 3"); People xiaoWang = new Renter (mediator, "Xiao Wang") Mediator.registerLandlord (laoWang, Message.builder (). Msg ("I have 2500 houses, downtown"). Build (); mediator.registerLandlord (laoBai, Message.builder (). Msg ("I have 2000 houses, next to the subway"). Build (); mediator.registerLandlord (laoLee, Message.builder (). Msg ("I have 2000 houses, floor balcony, large space, good lighting, subway side"). Build ()) Mediator.registerRenter (xiaoSan); log.info ("Xiao 3 starts looking for a house"); xiaoSan.sendMessage (Message.builder (). Msg ("looking for a house that rents for 2000 yuan a month, close to the subway"). Build (); log.info ("not long before-Lao Bai upgraded the housing information") LaoBai.sendMessage (Message.builder (). Msg ("I have a 2000 house, next to the subway, I have air conditioning and water heater"). Build (); mediator.registerRenter (xiaoWang); log.info ("Xiao Wang starts looking for a house"); xiaoWang.sendMessage (Message.builder (). Msg ("want to rent a house for 2500 yuan a month, close to the subway"). Build ()) Log.info ("before long-Lao Li also upgraded the house information"); laoBai.sendMessage (Message.builder (). Msg ("I have 2000 houses, floor-to-floor balcony, large space, good lighting, next to the subway, I also have air conditioning and water heater"). Build ();}}

The final results are as follows

Now let me analyze the roles of the characters in it:

First analyze two abstract classes. The abstract colleague class, which contains the name and the reference of the intermediary, has two methods to take and send information to the intermediary from the intermediary. Abstract intermediary, which contains the map information of the landlord, key is the landlord data, value is the landlord's housing information, used for landlord registration and landlord housing information changes; tenant list information, for tenant registration, while there is a coordination method to coordinate landlords and tenants.

The concrete abstract class (real estate intermediary) realizes the coordination method of the abstract intermediary, when the tenant sends the message, sends the tenant's rental condition information to all landlords and the tenant receives the housing information of all landlords there; when the landlord sends the message, the landlord's house information is sent to all tenants to change the landlord's housing information in the intermediary at the same time.

The concrete colleague implementation class (landlord and tenant) implements the methods of reading and sending messages of the abstract colleague class (the house is implemented by the coordination method of the intermediary).

Application in JDK

Distribute messages and reduce direct dependencies between classes by using an intermediate object.

Java.util.Timer

Java.util.concurrent.Executor#execute ()

Java.util.concurrent.ExecutorService#submit ()

Java.lang.reflect.Method#invoke ()

Summarize the advantages

Using the mediator pattern, you can encapsulate the interaction between colleague objects into the intermediary object, thus loosely coupling the colleague objects.

The mediator pattern can change the original many-to-many colleague object relationship into the intermediary object-to-many colleague object relationship, which makes the relationship between objects easier to understand and implement.

The interactions between colleague objects are encapsulated into intermediary objects for centralized management and centralized control of interactions. When the interaction changes, the focus is on modifying the intermediary object. When you need to extend the intermediary object, other colleague objects do not need to be modified.

Shortcoming

If you have more co-workers, the interaction is more complex. Intermediaries can be large and complex to maintain.

Referenc

Intermediary mode | Rookie tutorial

Mediator pattern

Count the design patterns in JDK

Intermediary pattern of JAVA design pattern [Mediator Pattern]

Welcome to follow us.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report