Skip to content

Instantly share code, notes, and snippets.

@kciesielski
Created November 22, 2012 20:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kciesielski/4132828 to your computer and use it in GitHub Desktop.
Save kciesielski/4132828 to your computer and use it in GitHub Desktop.
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;
}
@Override
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) {
super(decorated);
if (rebateValue.greaterThan(minimalThreshold))
throw new IllegalArgumentException(
"Rabate can't be graterThan minimal threshold");
this.minimalThreshold = minimalThreshold;
this.rebateValue = rebateValue;
}
@Override
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