First, what is the responsibility chain model?
The chain of responsibility mode refers to multiple objects, which can sequentially process the information passed in and pass it on to the next object until the processing is complete.
Ii. What are the roles of the chain of responsibility?
- Abstract processor role: Defines an interface for processing requests, and, if necessary, defines a method for setting and returning the next processor
- Specific processor role: When a request is received by a specific processor, you can choose to dispose of the request or pass the request to the next processor
Third, the code detailed:
Abstract class:
Public Abstract classHandler {/*** Next Processor*/ PrivateHandler Target; PublicHandler Gettarget () {returnTarget; } Public voidsettarget (Handler target) { This. target =Target; } Public Abstract voidprocess ();}
Specific implementation of a:
Public class extends Handler { @Override publicvoid process () { = gettarget (); ifnull) { System.out.println ("A processing, directly returns the result"); return ; Else { System.out.println ("A processing, return to the next handler continue processing"); Handler.process (); }}}
Concrete Implementation B:
Public class extends handler{ @Override publicvoid process () { = gettarget (); ifnull) { System.out.println ("b after processing, directly returning the result") ; return ; Else { System.out.println ("B" after processing, return to the next handler continue processing "); Handler.process (); }}}
Client:
Public class Client { publicstaticvoid main (string[] args) { new handler_a (); New Handler_b (); Handlera.settarget (Handlerb); Handlera.process (); } }
Results Print:
After a processing, returns the next handler continues processing B processing, returns the result directly
The model of responsibility chain in Java design pattern