I wrote the following code:
package com.chain;
public interface Chain {
void setNext(Chain chain);
void process(int number);
}
package com.chain;
public class ProcessNegative implements Chain{
private Chain chain;
public void setNext(Chain chain){
this.chain = chain;
}
public void process(int number){
if(number < 0){
System.out.println("Negative");
}else{
chain.process(number);
}
}
}
package com.chain;
public class ProcessPositive implements Chain{
private Chain chain;
public void setNext(Chain chain){
this.chain = chain;
}
public void process(int number){
if(number>0){
System.out.println("Positive");
}else{
chain.process(number);
}
}
}
package com.chain;
public class ProcessZero implements Chain{
private Chain chain;
public void setNext(Chain chain){
this.chain = chain;
}
public void process(int number){
if(number==0){
System.out.println("Positive");
}else{
chain.process(number);
}
}
}
package com.chain;
public class Test {
public static void main(String[] args){
Chain c1 = new ProcessNegative();
Chain c2 = new ProcessZero();
Chain c3 = new ProcessPositive();
c1.setNext(c2);
c2.setNext(c3);
c1.process(-1);
c2.process(5);
c3.process(1);
}
}
If I change c3 process value from 1 to -1, I get an exception. Isn't other objects in the chain suppose to process the value?
Your help is kindly appreciated.
Thank You.