Java implements 23 design patterns: responsibility chain pattern

Keywords: Java

Classification of 23 design patterns

1, Overview

The definition of Chain of Responsibility mode: in order to avoid the coupling of request sender and multiple request processors, all request processors are connected into a chain by remembering the reference of their next object through the previous object; when a request occurs, the request can be passed along the chain until it is processed by an object.

In the responsibility chain mode, the customer only needs to send the request to the responsibility chain, and does not care about the details of the request processing and the transfer process of the request, so the responsibility chain decouples the sender of the request and the processor of the request.

advantage

  • It reduces the coupling between objects. This pattern makes it unnecessary for an object to know which object handles its request and the structure of its chain, and neither the sender nor the receiver has the clear information of the other.
  • Enhance the scalability of the system. New request processing classes can be added as needed to meet the opening and closing principle.
  • Increased flexibility in assigning responsibilities to objects. When the workflow changes, you can dynamically change the members of the chain or transfer their order, or dynamically add or delete responsibilities.
  • The responsibility chain simplifies the connection between objects. Each object only needs to keep a reference to its successor, not to keep the references of all other processors, which avoids using many if or if... else statements.
  • Responsibility sharing. Each class only needs to deal with its own work, and the work that should not be dealt with is passed to the next object for completion. The responsibility scope of each class is clear, which conforms to the single responsibility principle of the class.

shortcoming

  • There is no guarantee that every request will be processed. Since a request has no clear receiver, there is no guarantee that it will be processed. The request may not be processed all the way to the end of the chain.
  • For a relatively long responsibility chain, the processing of requests may involve multiple processing objects, and the system performance will be affected to some extent.
  • The rationality of responsibility chain establishment depends on the client, which increases the complexity of the client, and may lead to system error due to the wrong setting of responsibility chain, such as circular call.

scene

1. There are multiple objects that can handle the same request, and which object handles the request is automatically determined by the runtime.
2. Submit a request to one of multiple objects without explicitly specifying the recipient.
3. You can dynamically specify a set of objects to process requests.

2, Implementation

1. Structure diagram

The responsibility chain mode mainly includes the following roles:

  • Abstract Handler role: defines an interface for processing requests, including abstract processing methods and a subsequent connection.
  • Concrete Handler role: implement the processing method of the abstract handler to determine whether the request can be processed. If the request can be processed, it will be processed. Otherwise, the request will be transferred to its successor.
  • Client role: create a processing chain and submit a request to the specific handler object of the chain head. It does not care about the details of processing and the transfer process of the request.

PS: the UML structure diagram can be referred to. The example implementation is not completed according to the UML diagram, and it can be implemented flexibly;

2. Implementation

  • Multiple filters
package cn.missbe.model.responsibilityChain.filter;

/**
 * Copyright (c) 2020.
 * Email: love1208tt@foxmail.com
 * @author lyg  2020/4/27 7:21 PM
 * description:
 * Responsibility chain mode: specific Filter
 **/

public interface Filter {
    boolean doFilter(Message msg);
}
/**Smiley face filter*/
public class FaceFilter implements Filter {
    @Override
    public boolean doFilter(Message msg) {
        msg.setMsg(msg.getMsg().replace(":(", "^_^"));
        return true;
    }
}
/**Html Character filter*/
public class HtmlFilter implements  Filter {
    @Override
    public boolean doFilter(Message msg) {
        msg.setMsg(msg.getMsg().replaceAll("<","["));
        msg.setMsg(msg.getMsg().replaceAll(">","]"));
        return true;
    }
}
/**Sensitive word filter*/
public class SensitiveFilter implements Filter {
    @Override
    public boolean doFilter(Message msg) {
        if (msg.getMsg().contains("996")) {
            return false;
        }
        return true;
    }
}
  • Filter responsibility chain
package cn.missbe.model.responsibilityChain.filter;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Copyright (c) 2020.
 * Email: love1208tt@foxmail.com
 * @author lyg  2020/4/27 7:33 PM
 * description:
 * Filter chain
 **/

public class FilterChain {
    private List<Filter> filterChain = new ArrayList<>();

    public FilterChain registerFilter(Filter filter) {
        filterChain.add(filter);
        return this;
    }

    public boolean doFilter(Message msg){
        for (Filter filter : filterChain) {
            if (!filter.doFilter(msg)) {
                return false;
            }
        }
        return true;
    }
}
  • Main main class
package cn.missbe.model.responsibilityChain.filter;

/**
 * Copyright (c) 2020.
 * Email: love1208tt@foxmail.com
 * @author lyg  2020/4/27 7:30 pm
 * description:
 * Responsibility chain model
 **/

public class Main {
    public static void main(String[] args) {
        Message message = new Message();
        message.setMsg("Filter test,<script>smiling face:(,This is a sensitive word 996.</script>");
        FilterChain filterChain = new FilterChain();
        filterChain.registerFilter(new HtmlFilter()).registerFilter(new FaceFilter()).registerFilter(new SensitiveFilter());
        filterChain.doFilter(message);
        System.out.println(message);
    }
}

Posted by drcphd on Fri, 05 Jun 2020 01:10:14 -0700