1、我们先定义工序(Procedure)这样一个接口类:
public interface Procedure {
public abstract void nextProcedure(Procedure procedure); //下一工序
public abstract void executeProcedure(String aim); //执行工序
}
2、定义工序(Procedure)接口的实现类:
A:分析设计工序(DesignProcedure)
public class DesignProcedure implements Procedure {
private Procedure nextProcedure = null;
private String procedureName = "Design"; //该工序名
public void nextProcedure(Procedure procedure) { //下一工序
nextProcedure = procedure;
}
public void executeProcedure(String currentProcedure) { //执行工序
if(currentProcedure.equals(procedureName)) {//如果当前工序和该工序相符
System.out.println("进行系统分析设计");
} else {
if(nextProcedure != null) { //如果当前工序和该工序不相符则转入下一工序
nextProcedure.executeProcedure(currentProcedure);
}
}
}
}
B:编码工序(CodeProcedure)
public class CodeProcedure implements Procedure {
private Procedure nextProcedure = null;
private String procedureName = "Code"; //该工序名
public void nextProcedure(Procedure procedure) { //下一工序
nextProcedure = procedure;
}
public void executeProcedure(String currentProcedure) { //执行工序
if(currentProcedure.equals(procedureName)) {//如果当前工序和该工序相符
System.out.println("进行编码工作");
} else {
if(nextProcedure != null) { //如果当前工序和该工序不相符则转入下一工序
nextProcedure.executeProcedure(currentProcedure);
}
}
}
}
C:测试工序(TestProcedure)
public class TestProcedure implements Procedure {
private Procedure nextProcedure = null;
private String procedureName = "Test"; //该工序名
public void nextProcedure(Procedure procedure) { //下一工序
nextProcedure = procedure;
}
public void executeProcedure(String currentProcedure) { //执行工序
if(currentProcedure.equals(procedureName)) {//如果当前工序和该工序相符
System.out.println("进行系统测试");
} else {
if(nextProcedure != null) { //如果当前工序和该工序不相符则转入下一工序
nextProcedure.executeProcedure(currentProcedure);
}
}
}
}
3、编写测试类:
public class test {
public static void main(String[] args) {
DesignProcedure design = new DesignProcedure(); //分析设计工序
CodeProcedure code = new CodeProcedure(); //编码工序
TestProcedure test = new TestProcedure(); //测试工序
design.nextProcedure(code); //定义分析设计工序的下一工序
code.nextProcedure(test); //定义编码工序的下一工序
design.executeProcedure("Design"); //开始执行工序
design.executeProcedure("Code");
design.executeProcedure("Test");
}
4、说明:
A: Chain of Responsibility定义:Chain of Responsibility模式是用一系列类(classes)试图处理一个请求request,这些类之间是一个松散的耦合,唯一共同点是在他们之间传递request.,也就是说,来了一个请求,A类先处理,如果没有处理,就传递到B类处理,如果没有处理,就传递到C类处理,就这样象一个链条 (chain)一样传递下去。