先附上代码:
- package com.hbq.chain;
- import java.util.ArrayList;
- import java.util.Random;
- interface IWomen
- {
- public int getType();
- public String getRequest();
- }
- class Women implements IWomen
- {
- private int type = 0 ;
- private String request = "" ;
- public Women(int type,String req)
- {
- this.type = type ;
- switch(this.type)
- {
- case 1:
- this.request = "女儿的请求是:"+req ;
- break;
- case 2:
- this.request = "妻子的请求是:"+req ;
- break;
- case 3:
- this.request = "母亲的请求是:"+req ;
- break;
- }
- }
- @Override
- public int getType() {
- // TODO Auto-generated method stub
- return this.type;
- }
- @Override
- public String getRequest() {
- // TODO Auto-generated method stub
- return this.request;
- }
- }
- public abstract class Handler {
- private int level = 0 ;
- private Handler next = null ;
- public Handler(int l,Handler n)
- {
- this.level = l ;
- this.next = n ;
- }
- public Handler(int level)
- {
- this.level = level ;
- }
- public void setNext(Handler next)
- {
- this.next = next ;
- }
- public abstract void response(IWomen women);
- /*每个环节只有2个选项:要么承担责任作出回应,要么向下传*/
- public void handleMsg(IWomen women)
- {
- if(this.level == women.getType())
- this.response(women);
- else
- {
- if( this.next != null )
- {
- this.next.handleMsg(women);
- }
- else
- System.out.println("-----------没有地方请示了,不做处理!-----------\n");
- }
- }
- }
- class Father extends Handler
- {
- public Father() {
- super(1);
- // TODO Auto-generated constructor stub
- }
- @Override
- public void response(IWomen women) {
- // TODO Auto-generated method stub
- System.out.println("-----------女儿向父亲请示------------");
- System.out.println(women.getRequest());
- System.out.println("父亲的回答是:同意\n");
- }
- }
- class Son extends Handler
- {
- public Son() {
- super(3);
- // TODO Auto-generated constructor stub
- }
- @Override
- public void response(IWomen women) {
- // TODO Auto-generated method stub
- System.out.println("-----------母亲向儿子请示------------");
- System.out.println(women.getRequest());
- System.out.println("儿子的回答是:同意\n");
- }
- }
- class Husband extends Handler
- {
- public Husband() {
- super(2);
- // TODO Auto-generated constructor stub
- }
- @Override
- public void response(IWomen women) {
- // TODO Auto-generated method stub
- System.out.println("-----------妻子向丈夫请示------------");
- System.out.println(women.getRequest());
- System.out.println("丈夫的回答是:同意\n");
- }
- }
- class client
- {
- public static void main(String[] args)
- {
- /*随机设置一些Women*/
- Random rand = new Random();
- ArrayList<IWomen> arrayList = new ArrayList();
- for( int i = 0 ; i < 5 ; i++)
- {
- int j = rand.nextInt(4) ;
- arrayList.add(new Women(j,"我要出去逛街"));
- //System.out.print(j);
- }
- //System.out.println("\n");
- Father father = new Father();
- Son son = new Son();
- Husband husband = new Husband();
- father.setNext(husband);
- husband.setNext(son);
- for( IWomen women:arrayList)
- {
- /*在责任链模式下,不用关注最终处理的对象是谁,由链表的形式往下传*/
- father.handleMsg(women);
- }
- }
- }