In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
In this article Xiaobian for you to introduce in detail the "Java chain of responsibility model example code analysis", the content is detailed, the steps are clear, the details are handled properly, I hope this "Java chain of responsibility model example code analysis" article can help you solve doubts, the following follow the editor's ideas slowly in-depth, together to learn new knowledge.
Advantages
1. Reduce the coupling degree. It decouples the sender and receiver of the request.
two。 Simplifies the object. So that the object does not need to know the structure of the chain.
3. Increase the flexibility of assigning responsibilities to objects. Allow the dynamic addition or removal of responsibilities by changing the members of the chain or transferring their order.
4. It is convenient to add a new request processing class.
Shortcoming
1. There is no guarantee that the request will be accepted.
two。 System performance will be affected to a certain extent, and it is not convenient to debug the code, which may result in circular calls.
3. It may not be easy to observe the characteristics of the runtime, hindering debugging.
Working with scen
1. There are multiple objects that can process the same request, and which object handles the request is automatically determined by the run time.
two。 Submit a request to one of multiple objects without explicitly specifying the recipient.
3. A set of objects can be dynamically specified to handle requests.
I. the way of realization
Suppose that in a school, the function of the principal is greater than that of the teacher, and the function of the teacher is greater than that of the student. based on this link, the things that the students can't handle are reported to the teacher, and the things that the teacher can't handle are reported to the principal.
1. Handle abstract class package com.asurplus.common.handle.style1;/** * handle abstract class * / public abstract class Handler {/ * next processing class * / protected Handler handler; public void setHandler (Handler handler) {this.handler = handler;} public Handler getHandler () {return handler } / * * handle events * * @ param request * / public abstract void handlerRequest (String request);} 2. Student processing package com.asurplus.common.handle.style1;import lombok.extern.slf4j.Slf4j / * Student processing class * / @ Slf4jpublic class StudentHandler extends Handler {@ Override public void handlerRequest (String request) {if ("cleaning" .equals (request)) {log.info ("student processing");} else {this.handler.handlerRequest (request);}
The student can handle the matter of "cleaning". If it is anything else, give him the next element.
3. Teacher processing class package com.asurplus.common.handle.style1;import lombok.extern.slf4j.Slf4j;/** * teacher processing class * / @ Slf4jpublic class TeacherHandler extends Handler {@ Override public void handlerRequest (String request) {if ("marking papers" .equals (request)) {log.info ("teacher processing");} else {this.handler.handlerRequest (request);}
The teacher can handle the matter of "correcting the test paper". If it is anything else, give him the next element.
4. Principal processing class package com.asurplus.common.handle.style1;import lombok.extern.slf4j.Slf4j;/** * Principal handling class * / @ Slf4jpublic class HeadHandler extends Handler {@ Override public void handlerRequest (String request) {if ("student status issues" .equals (request)) {log.info ("headmaster processing");} else {log.error ("unable to handle the event") }}}
The headmaster can deal with the issue of "student status". If it is anything else, because our chain of responsibility has only three levels, we can't handle it, so we can only print logs.
5. Test package com.asurplus.common.handle.style1;/** * chain of responsibility mode * / public class TestMain {public static void main (String [] args) {/ / Student processor StudentHandler studentHandler = new StudentHandler (); / teacher processor TeacherHandler teacherHandler = new TeacherHandler (); / / Principal processor HeadHandler headHandler = new HeadHandler () / / the teacher's superior level is the principal teacherHandler.setHandler (headHandler); / / the student's superior level is the teacher studentHandler.setHandler (teacherHandler); / / the matter of correcting the examination paper is studentHandler.handlerRequest ("correcting the examination paper");}}
Output result
It can be seen that the matter of "correcting examination papers" was dealt with by the teacher.
Second, the mode of realization
Suppose a scenario, in our e-commerce system, when creating an order, we need to check a lot of data, we need to determine whether the product exists, whether the stock is still available, whether the price is correct, and so on.
1. Order information package com.asurplus.common.handle.style2;import lombok.Builder;import lombok.Data;/** * order information * / @ Data@Builderpublic class Order {/ / inventory private int stock; / / unit price private int price;} 2, order verification API package com.asurplus.common.handle.style2 / * @ param * / public interface OrderFilter {/ * business logic * * @ param t * @ return * / boolean execute (T t);} 3, inventory verifier package com.asurplus.common.handle.style2;import lombok.extern.slf4j.Slf4j / * inventory verifier * / @ Slf4jpublic class OrderStockFilter implements OrderFilter {@ Override public boolean execute (Order order) {if (0 > = order.getStock ()) {log.error ("insufficient inventory"); return false;} return true;}} 4, price verifier package com.asurplus.common.handle.style2;import lombok.extern.slf4j.Slf4j / * Price verifier * / @ Slf4jpublic class OrderPriceFilter implements OrderFilter {@ Override public boolean execute (Order order) {if (0 > order.getPrice ()) {log.error ("price error"); return false;} return true;}} 5, Test package com.asurplus.common.handle.style2;import lombok.extern.slf4j.Slf4j;import java.util.Arrays;import java.util.List / * responsibility chain mode * / @ Slf4jpublic class TestMain {public static void main (String [] args) {/ / Builder mode to create an order Order order = Order.builder (). Stock (0) .price (0). Build (); / / inventory verifier OrderStockFilter orderQuantityFilter = new OrderStockFilter (); / / Price verifier OrderPriceFilter orderPriceFilter = new OrderPriceFilter () / / assemble a list List orderFilters = Arrays.asList (orderQuantityFilter, orderPriceFilter); boolean res = false; / / Loop check for (OrderFilter item: orderFilters) {res = item.execute (order); / / stop checking if (! res) {break if any of these items fail }} if (! res) {log.error ("failed to place order");}
Failed to be checked by our "inventory verifier", resulting in failure to place the order.
Read this, the "Java chain of responsibility model example code analysis" article has been introduced, want to master the knowledge of this article also need to practice and use to understand, if you want to know more about the article, welcome to follow the industry information channel.
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.