Many objects have a link to each object's reference to its next generation, and the request is passed through the chain until an object on the chain decides to process the request, such as a scenario such as a unit approval process.
Key points: 1) abstract processor role: Define processing request interface and set a referral
2) Specific handling of the role: specific processing requests or choose to pass the request to the
1. Abstract processor role class, define processing request interface and reference
Public Abstract classPricehandle {protectedPricehandle successor; Public voidSetsuccessor (Pricehandle successor) { This. successor =successor; } Public Abstract voidProcessfloatdiscount); Public StaticPricehandle Createpricehandle () {Pricehandle sales=NewSales (); Pricehandle Direct=NewDirect (); Pricehandle CEO=NewCEO (); Sales.setsuccessor (direct); Direct.setsuccessor (CEO); returnsales; }}
2. Specific processor role Category sales category
Public class extends Pricehandle { publicvoid process (float discount) { if (Discount <= 0.1) { System.out.format ("%s approved discount:%.2f%n", this. GetClass (). GetName (), discount); Else { successor.process (discount); }}}
3. Specific Processor Role Supervisor class
Public class extends Pricehandle { publicvoid process (float discount) { if (Discount <= 0.2) { System.out.format ("%s approved discount:%.2f%n", this. GetClass (). GetName (), discount); Else { successor.process (discount); }}}
4. Specific Processor Role CEO category
Public class extends Pricehandle { publicvoid process (float discount) { if (Discount <= 0.3) { System.out.format ("%s approved discount:%.2f%n", this. GetClass (). GetName (), discount); Else { System.out.format ("%s declined discount:%.2f%n", this. GetClass (). GetName (), discount);} } }
5. Test class
Public classModel {PrivatePricehandle Pricehandle; Public voidSetpricehandle (Pricehandle pricehandle) { This. Pricehandle =Pricehandle; } Public voidRequestdiscount (floatdiscount) {pricehandle.process (discount); } Public Static voidMain (string[] args) {Model customer=NewModel (); Customer.setpricehandle (Pricehandle.createpricehandle ()); Random Random=NewRandom (); for(inti = 0; I < 100; i++) {System.out.print (i+ ":"); Customer.requestdiscount (Random.nextfloat ()); } }}
Java design Pattern (v) Responsibility chain model