Responsibility chain Pattern: Multiple objects are linked by the reference of their objects to the next, and the request is passed on this chain until one of the receiving objects on the chain processes the request. Because the requesting client does not know who is ultimately on the chain to process the request, the system can dynamically rearrange and assign responsibilities without affecting the client, thus avoiding coupling between the requesting sender and the request processor.
There are three kinds of roles involved in the chain of responsibility:
1, abstract processor role
2, the specific processor role
3, Request sender
Small example: Suppose to buy a house, buy a house need to bargain, sell the person position is different, can preferential price also different, different positions can form a processing request chain. We tentatively: * Basic sales staff, only preferential 3% * Sales Manager: can offer 5% * Sales Director: can offer 8% * Boss: Discount 10%
Java instance
class Diagram:
/**
* Abstract Responsibility * * Public
abstract class IFilter {
private IFilter successor;
Public IFilter Getsuccessor () {return
successor;
}
public void Setsuccessor (IFilter successor) {
this.successor = successor;
}
public abstract void Handlefilter ();
public abstract void HandleFilter2 ();
}
/** * Specific Liability */public class Concretefilter extends IFilter {private String n
Ame
Public Concretefilter (String name) {this.name = name; The @Override public void Handlefilter () {/* * is processed by itself, if any successor, and then handled by it once/System.out.println (NA
Me + "process request");
if (getsuccessor ()!= null) {Getsuccessor (). Handlefilter (); @Override public void HandleFilter2 () {/* * * * * has successors to deal with successors, otherwise deal with/if (getsuccessor
()!= null) {Getsuccessor (). HandleFilter2 ();
else {System.out.println (name + "process request"); }
}
}
public class Test {public
static void Main (string[] args) {
IFilter filter1 = new Concretefilter ("Permission-filt //Permission filter
IFilter filter2 = new Concretefilter ("Suffix-filter");/suffix name filter
IFilter filter3 = new Concretefilter ("Style-filter");//Style filter
filter1.setsuccessor (filter2);
Filter2.setsuccessor (FILTER3);
SYSTEM.OUT.PRINTLN ("------The following are dealt with by each of the handlers (including successors), and in the order that they are delivered at one level------");
Filter1.handlefilter ();
SYSTEM.OUT.PRINTLN ("------The following is referred to the last successor------");
Filter1.handlefilter2 ();
}
Print:
------The following are processed by each processor (including successors), and the order is one level of delivery------
Permission-filter processing the request
Suffix-filter processing the request
Style-filter processed the request
------The following is referred to the last successor------
style-filter processed the request