Chain of Responsibility Design Pattern
The Chain of Responsibility is a behavioral design pattern. It allows a request to pass through a chain of handlers, where every handler either processes the request or passes it to the next handler in the chain. It follows responsibility delegation.
In the below example, we will manufacture a bat in multiple steps. In the first step a plain bat will be made. The next handler will apply handle grip to it. The next will apply brand sticker to it.
Bat.java
package com.sks.cor;
public class Bat {
private int length;
private int breadth;
private boolean isGripApplied;
private boolean isStickerApplied;
//constructors
//getters a
}
ManufacturingChain interface
package com.sks.cor;
public interface ManufacturingChain {
void setNextChain(ManufacturingChain nextChain, Bat bat);
Bat manufacture();
}
WillowManufacturer.java
package com.sks.cor;
public class WillowManufacturer implements ManufacturingChain {
private Bat bat;
private ManufacturingChain chain;
@Override
public void setNextChain(ManufacturingChain nextChain, Bat bat) {
this.chain = nextChain;
this.bat = bat;
}
@Override
public Bat manufacture() {
this.bat.setLength(38); // these dimensions are in inches
this.bat.setBreadth(4);
if (this.chain == null)
return this.bat;
else
return this.chain.manufacture();
}
}
HandleGripApplier.java
package com.sks.cor;
public class HandleGripApplier implements ManufacturingChain {
private Bat bat;
private ManufacturingChain chain;
@Override
public void setNextChain(ManufacturingChain nextChain, Bat bat) {
this.chain = nextChain;
this.bat = bat;
}
@Override
public Bat manufacture() {
bat.setGripApplied(true);
if (this.chain == null)
return this.bat;
else
return this.chain.manufacture();
}
}
BrandStickerApplier.java
package com.sks.cor;
public class BrandStickerApplier implements ManufacturingChain {
private ManufacturingChain chain;
private Bat bat;
@Override
public void setNextChain(ManufacturingChain nextChain, Bat bat) {
this.chain = nextChain;
this.bat = bat;
}
@Override
public Bat manufacture() {
this.bat.setStickerApplied(true);
if (this.chain == null)
return this.bat;
else
return this.chain.manufacture();
}
}
BatManufacturer.java
package com.sks.cor;
public class BatManufacturer {
private ManufacturingChain startChain;
public BatManufacturer() {
Bat bat = new Bat();
this.startChain = new WillowManufacturer();
ManufacturingChain gripChain = new HandleGripApplier();
startChain.setNextChain(gripChain, bat);
ManufacturingChain stickerChain = new BrandStickerApplier();
gripChain.setNextChain(stickerChain, bat);
stickerChain.setNextChain(null, bat);
}
public static void main(String[] args) {
BatManufacturer batManufacturer = new BatManufacturer();
Bat bat = batManufacturer.startChain.manufacture();
System.out.println(bat);
}
}
Output :