一个责任链模式

package com.modle.basehandle;

public abstract class Handler { public static final int FATHER_LEVEL = 1; public static final int HANS_LEVEL = 2; public static final int SON_LEVEL = 3; private int level = 0; private Handler nextHandler = null; public Handler(int level) { this.level = level; } public void setNextHandler(Handler handler) { this.nextHandler = handler; } protected abstract void response(IWoman iWoman); public void handleMessage(IWoman iWoman) { if(iWoman.getType() == this.level) { this.response(iWoman); } else { if(this.nextHandler != null) { // this.nextHandler.response(iWoman); this.nextHandler.handleMessage(iWoman); } else { System.out.println("没有对象处理结果!"); } } } } 
package com.modle.basehandle;

public class Father extends Handler { public Father() { super(FATHER_LEVEL); } @Override protected void response(IWoman iWoman) { System.out.println(iWoman.getRequest()); System.out.println("Father yes!"); } } 
package com.modle.basehandle;

public class Hus extends Handler { public Hus() { super(HANS_LEVEL); } @Override protected void response(IWoman iWoman) { System.out.println(iWoman.getRequest()); System.out.println("hus yes"); } } 
package com.modle.basehandle;

public class Son extends Handler { public Son() { super(SON_LEVEL); } @Override protected void response(IWoman iWoman) { System.out.println(iWoman.getRequest()); System.out.println("son yes"); } } 
package com.modle.basehandle;

public interface IWoman { int getType(); String getRequest(); } 
package com.modle.basehandle;

public class Woman implements IWoman { private int type = 0; private String request = ""; public Woman(int type, String request) { this.type = type; switch (this.type){ case 1: this.request = "女儿的请求是: " + request; break; case 2: this.request = "妻子的请求是: " + request; break; case 3: this.request = "母亲的请求是: " + request; break; } } @Override public int getType() { return this.type; } @Override public String getRequest() { return this.request; } } 
package com.modle.basehandle;

import com.modle.human.Human;
import org.omg.CORBA.INTERNAL;

import java.util.ArrayList;
import java.util.List; import java.util.Random; public class Client { public static void main(String[] args) { // Random random = new Random(4); // List<Integer> list = new ArrayList<>(); // for(int i = 0; i < 6; i ++) { // list.add(random.nextInt()); // } // IWoman iWoman = new Woman(2,"逛街"); // IWoman iWoman = new Woman(1,"逛街"); IWoman iWoman = new Woman(3,"逛街"); Father father = new Father(); Hus hus = new Hus(); Son son = new Son(); father.setNextHandler(hus); hus.setNextHandler(son); father.handleMessage(iWoman); } } 
 来源: 扬州网站优化

猜你喜欢

转载自www.cnblogs.com/vwvwvwgwg/p/12892314.html