Friday 31 October 2014

Chain of responsibility pattern


Chain-of-responsibility pattern is a design pattern consisting of a source of command objects and a series of processing objects. Once client submits the request, the request is sent from one object to another making them parts of a chain and each object in this chain can handle the command, pass it on or do both.



Key Points in Chain of Responsibility pattern
1.   Clients don’t know which object in the chain will serve its request.

2.   Every node/handler/object in chain will have the responsibility to decide, if they can serve the request.

3.   If node/handler/object decides to forward the request, it should be capable of choosing the next node/handler/object and forward it.


Number.java
public interface Number {
    void process(int num);
    void setRequest(Number num);
}


EvenNumber.java
public class EvenNumber implements Number{
    private Number num;

    @Override
    public void process(int n) {
        if(n%2 == 0){
            System.out.println("Even Number");
        }
        else{
            num.process(n);
        }
    }

    @Override
    public void setRequest(Number num) {
       this.num = num;
    }

}


OddNumber.java
public class OddNumber implements Number {

    Number num;
   
    @Override
    public void process(int n) {
        if(isPrime(n)){
            num.process(n);
        }
        else{
            System.out.println("Odd Number");
        }
    }

     public boolean isPrime(int number){
        for(int i=2; i<=number/2; i++){
            if(number % i == 0){
                return false;
            }
        }
        return true;
    }

    @Override
    public void setRequest(Number num) {
       this.num = num;
    }

}


PrimeNumber.java
public class PrimeNumber implements Number {

    Number num;

    @Override
    public void process(int n) {
        System.out.println("Prime Number");
    }

    @Override
    public void setRequest(Number num) {
       this.num = num;
    }
}


ChainOfResponsibility.java
public class ChainOfResponsibility {
    public static void main(String args[]){
        Number evenNum = new EvenNumber();
        Number oddNum = new OddNumber();
        Number prime = new PrimeNumber();

        evenNum.setRequest(oddNum);
        oddNum.setRequest(prime);

        evenNum.process(9);
        evenNum.process(10);
        evenNum.process(11);
    }
}


Output
Odd Number
Even Number
Prime Number


No comments:

Post a Comment