Java design mode-Chain of duties (Responsibility)
The responsibility chain mode is an object behavior mode. In the responsibility chain mode, many objects are connected by each object's reference to its next home to form a chain. Requests are transmitted on this chain until an object on the chain decides to process this request. The client that sends this request does not know which object on the chain will eventually process this request, which allows the system to dynamically reorganize and assign responsibilities without affecting the client.
Structure of the responsibility chain model:
The source code is as follows:
Public abstract class Handler {/*** holding the successor responsibility object */protected Handler successor;/*** indicates the request processing method, although this method does not include parameters, however, parameters can be passed. * @ author Fu yuwei * @ time 09:34:35 */public abstract void handlRequest (); public Handler getSuccessor () {return successor;} public void setSuccessor (Handler successor) {this. successor = successor ;}}
Public class ConcreteHandler extends Handler {@ Override public void handlRequest () {// determines whether there is any successor responsibility object. If so, the request is forwarded to the successor object, if not, the request if (super. getSuccessor ()! = Null) {System. out. println ("disallow requests, request forwarding... "); getSuccessor (). handlRequest ();} else {System. out. println ("processing requests... ");}}}
Public class Client {/*** @ author Fu yuwei * @ time 09:38:59 * @ param args */public static void main (String [] args) {Handler handler1 = new ConcreteHandler (); Handler handler2 = new ConcreteHandler (); handler1.setSuccessor (handler2); handler1.handlRequest ();}}
/*** @ Author Fu yuwei * @ time 09:38:59 * @ param args */public static void main (String [] args) {Handler handler1 = new ConcreteHandler (); handler handler2 = new ConcreteHandler (); handler1.setSuccessor (handler2); handler1.handlRequest ();}
The sequence diagram of the above activities is as follows:
This article will be updated later if I encounter good examples.