Skip to content

Instantly share code, notes, and snippets.

Created November 22, 2012 20:29
What would you like to do?
Decorator Pattern example
public abstract class RebateDecorator implements RebatePolicy {
protected RebatePolicy decorated;
protected RebateDecorator(RebatePolicy decorated){
this.decorated = decorated;
public interface RebatePolicy {
Money calculateRebate(Product product, int quantity, Money regularCost);
public class StandardRebate implements RebatePolicy {
private BigDecimal rebateRatio;
private int mininalQuantity;
public StandardRebate(double rebate, int mininalQuantity) {
rebateRatio = new BigDecimal(rebate / 100);
this.mininalQuantity = mininalQuantity;
public Money calculateRebate(Product product, int quantity,
Money regularCost) {
if (quantity >= mininalQuantity)
return regularCost.multiplyBy(rebateRatio);
return Money.ZERO;
public class VipRebate extends RebateDecorator{
private Money minimalThreshold;
private Money rebateValue;
public VipRebate(Money minimalThreshold, Money rebateValue) {
this(null, minimalThreshold, rebateValue);
public VipRebate(RebatePolicy decorated, Money minimalThreshold,
Money rebateValue) {
if (rebateValue.greaterThan(minimalThreshold))
throw new IllegalArgumentException(
"Rabate can't be graterThan minimal threshold");
this.minimalThreshold = minimalThreshold;
this.rebateValue = rebateValue;
public Money calculateRebate(Product product, int quantity,
Money regularCost) {
Money baseValue = (decorated == null)
? regularCost
: decorated.calculateRebate(product, quantity, regularCost);
if (baseValue.greaterThan(minimalThreshold))
return baseValue.subtract(rebateValue);
return baseValue;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment