一連の責任パターンは、要求メッセージを処理するための動作を提供できるかどうか、および潜在的にそれを処理できるかにかかっています。ハンドラがリクエストを処理できない場合、代わりに次のカプセル化されたハンドラを呼び出します
2 つのコア コンポーネントは、インターフェイスと具象です。
interface IMoneyHandler {
void issueNotes(int money);
void setNext(IMoneyHandler handler);
}
具体的な実装の例は次のとおりです-
class TwentyMoneyHandler implements IMoneyHandler {
private IMoneyHandler nextHandler;
@Override
public void issueNotes(int money) {
int handlingAmount = 20;
// Test if we can handle the amount appropriately, otherwise delegate it
if(money >= handlingAmount) {
int dispenseNotes = money / handlingAmount;
System.out.println(dispenseNotes + " £20s dispenses");
int remainder = money % handlingAmount;
// Propagate the information to the next handler in the chain
if(remainder > 0) {
callNext(remainder);
}
} else {
// call the next handler if we can not handle it
callNext(money);
}
}
// Attempts to call the next if there is money left
private void callNext(int remainingMoney) {
// Note, there are different ways of null handling
// IE throwing an exception, or explicitly having a last element
// in the chain which handles this scenario
if(nextHandler != null) {
nextHandler.issueNotes(remainingMoney);
}
}
@Override
public void setNext(IMoneyHandler handler) {
this.nextHandler = handler;
}
}
現実の世界では、コードの重複を避けるために、これに対して抽象的な実装を提供する場合があることに注意してください。