Chain Of Responsibility design pattern in java with example



You are here : HomeCore Java Tutorials

In this article we will discuss the Chain Of Responsibility design pattern in java with example.

Example of Dispensing money from ATM.

Let's suppose Atm has 100, 50 and 10 notes.

And we want to dispense 1080, it will dispense
dispensing 100 = 10 note
dispensing 50 = 1 note
dispensing 10 = 3 note

And if we want to dispense 160, it will dispense
dispensing 100 = 1 note
dispensing 50 = 1 note
dispensing 10 = 1 note

We will chain 100 to 50 to 10, so we check for maximum possible 100notes first, then 50 then 10.

Using
rs100.nextRs = rs50;
rs50.nextRs = rs10;

Program of Chain Of Responsibility design pattern in java 

package chainOfRes;

abstract class Rs {

    int rs;

    abstract void message(int amount);

    Rs nextRs;

}

class Rs100 extends Rs {

    Rs100(int i) {
          this.rsi;
    }

    void message(int amount) {
          if (amount >= 100) {
                 System.out.println("dispensing 100 = "amount / 100);
                 amountamount - 100 * (amount / 100);
          }
          nextRs.message(amount);
    }

}

class Rs50 extends Rs {

    Rs50(int i) {
          this.rsi;
    }

    void message(int amount) {
          if (amount >= 50) {
                 System.out.println("dispensing 50 = "amount / 50);
                 amountamount - 50 * (amount / 50);
          }
          nextRs.message(amount);

    }

}

class Rs10 extends Rs {

    Rs10(int i) {
          this.rsi;
    }

    void message(int amount) {
          if (amount >= 10) {
                 System.out.println("dispensing 10 = "amount / 10);
                 amountamount - 10 * (amount / 10);
          }
          System.out.println("done");
    }

}

class ChainOfResponsibilityAtmMoneyDispense {
    public ChainOfResponsibilityAtmMoneyDispense() {
    }

    public static void main(String[] args) {
          Rs rs100new Rs100(100);
          Rs rs50new Rs50(50);
          Rs rs10new Rs10(10);

          //CHAINING
          rs100.nextRsrs50;
          rs50.nextRsrs10;

          rs100.message(1180);

    }
}

//OUTPUT
dispensing 100 = 11
dispensing 50 = 1
dispensing 10 = 3
done



eEdit
Must read for you :