Decorator Pattern example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public abstract class RebateDecorator implements RebatePolicy { | |
protected RebatePolicy decorated; | |
protected RebateDecorator(RebatePolicy decorated){ | |
this.decorated = decorated; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public interface RebatePolicy { | |
Money calculateRebate(Product product, int quantity, Money regularCost); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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