File tree Expand file tree Collapse file tree 5 files changed +74
-0
lines changed
src/com/anxpp/designpattern/chainofresponsibility Expand file tree Collapse file tree 5 files changed +74
-0
lines changed Original file line number Diff line number Diff line change 1+ package com .anxpp .designpattern .chainofresponsibility ;
2+ //处理者
3+ public interface Handler {
4+ int handleRequest (int n );
5+ void setNextHandler (Handler next );
6+ }
Original file line number Diff line number Diff line change 1+ package com .anxpp .designpattern .chainofresponsibility ;
2+ //第一个具体处理者,处理小于0的
3+ public class Handler1 implements Handler {
4+ private Handler next ;
5+ @ Override
6+ public int handleRequest (int n ){
7+ if (n <0 ) return -n ;
8+ else {
9+ if (next ==null )
10+ throw new NullPointerException ("next 不能为空" );
11+ return next .handleRequest (n );
12+ }
13+ }
14+ @ Override
15+ public void setNextHandler (Handler next ){
16+ this .next = next ;
17+ }
18+ }
Original file line number Diff line number Diff line change 1+ package com .anxpp .designpattern .chainofresponsibility ;
2+ //第二个具体处理者,处理>=0但小于10的
3+ public class Handler2 implements Handler {
4+ private Handler next ;
5+ @ Override
6+ public int handleRequest (int n ){
7+ if (n <10 ) return n *n ;
8+ else {
9+ if (next ==null )
10+ throw new NullPointerException ("next 不能为空" );
11+ return next .handleRequest (n );
12+ }
13+ }
14+ @ Override
15+ public void setNextHandler (Handler next ){
16+ this .next = next ;
17+ }
18+ }
Original file line number Diff line number Diff line change 1+ package com .anxpp .designpattern .chainofresponsibility ;
2+ //第三个具体处理者,处理>=0但小于10的
3+ public class Handler3 implements Handler {
4+ private Handler next ;
5+ @ Override
6+ public int handleRequest (int n ){
7+ if (n <=Integer .MAX_VALUE ) return n ;
8+ else {
9+ if (next ==null )
10+ throw new NullPointerException ("next 不能为空" );
11+ return next .handleRequest (n );
12+ }
13+ }
14+ @ Override
15+ public void setNextHandler (Handler next ){
16+ this .next = next ;
17+ }
18+ }
Original file line number Diff line number Diff line change 1+ package com .anxpp .designpattern .chainofresponsibility ;
2+ public class TestUse {
3+ public static void main (String args []){
4+ Handler h1 ,h2 ,h3 ;
5+ h1 = new Handler1 ();
6+ h2 = new Handler2 ();
7+ h3 = new Handler3 ();
8+ h1 .setNextHandler (h2 );
9+ h2 .setNextHandler (h3 );
10+ System .out .println (h1 .handleRequest (-1 ));
11+ System .out .println (h1 .handleRequest (5 ));
12+ System .out .println (h1 .handleRequest (9999 ));
13+ }
14+ }
You can’t perform that action at this time.
0 commit comments