Template Pattern: Whenever we are using abstract classes in Java means we are implementing Template Pattern. Check out the below implementation.
package org.paandav.template;
import java.math.BigDecimal;
public abstract class TaxTemplate {
public BigDecimal getTotalTax() {
BigDecimal totalTax = new BigDecimal(0.0);
totalTax = getFedTax().add(getStateTax());
return totalTax;
}
public abstract BigDecimal getFedTax();
public abstract BigDecimal getStateTax();
}
package org.paandav.template;
import java.math.BigDecimal;
public class StateOneTax extends TaxTemplate{
@Override
public BigDecimal getFedTax() {
//Tax Calculation Logic
return new BigDecimal(10.11);
}
@Override
public BigDecimal getStateTax() {
//Tax Calculation Logic
return new BigDecimal(12.11);
}
}
package org.paandav.template;
import java.math.BigDecimal;
public class StateTwoTax extends TaxTemplate{
@Override
public BigDecimal getFedTax() {
//Tax Calculation Logic
return new BigDecimal(13.00);
}
@Override
public BigDecimal getStateTax() {
//Tax Calculation Logic
return new BigDecimal(19.66);
}
}
package org.paandav.template;
import java.math.BigDecimal;
public class TemplatePatternTest {
public static void main(String[] args) {
TaxTemplate stateOneTax = new StateOneTax();
TaxTemplate stateTwoTax = new StateTwoTax();
BigDecimal txAmtOne = stateOneTax.getTotalTax();
BigDecimal txAmtTwo = stateTwoTax.getTotalTax();
System.out.println("State One Tax = " + txAmtOne);
System.out.println("State Two Tax = " + txAmtTwo);
}
}
No comments:
Post a Comment