SE450: Strategy: Code [11/22] ![]() ![]() ![]() |
SalesOrder, the Context
package example.strategy;
public class SalesOrder {
// makes a bogus sales order and returns the tax
public double calcTax() {
String item1 = "book";
String item2 = "gum";
double item1qty = 2;
double item2qty = 4;
double item1price = 14.32;
double item2price = 0.34;
double totalTax = 0.0;
CalcTax taxer = Configuration.getTaxer();
totalTax += taxer.taxAmount(item1, item1qty, item1price);
totalTax += taxer.taxAmount(item2, item2qty, item2price);
return totalTax;
}
}
CalcTax, the Strategy
package example.strategy;
public interface CalcTax {
public double taxAmount(String item, double qty, double price);
}
USTax, CanTax = ConcreteStrategies
package example.strategy;
public class USTax implements CalcTax {
public double taxAmount(String item, double qty, double price) {
// crude algorithm
if("book".equals(item)) {
return qty * price * 0.04;
} else {
return qty * price * 0.05;
}
}
}
package example.strategy;
public class CanTax implements CalcTax {
public double taxAmount(String item, double qty, double price) {
// crude algorithm, Canada much more expensive than US!
if("book".equals(item)) {
return qty * price * 0.4;
} else {
return qty * price * 0.5;
}
}
}
Others: Configuration
package example.strategy;
public class Configuration {
// default to US
private static CalcTax taxer = new USTax();
public static CalcTax getTaxer() {
return taxer;
}
public static void setTaxer(String name) {
if("can".equals(name)) {
taxer = new CanTax();
} else {
taxer = new USTax();
}
}
}
TaskController: the driver
package example.strategy;
package example.strategy;
public class TaskController {
public static void main(String args[]) {
SalesOrder order = new SalesOrder();
Configuration.setTaxer("us");
System.out.println("The tax for the U.S. is " +
order.calcTax());
Configuration.setTaxer("can");
System.out.println("The tax for Canada is " +
order.calcTax());
}
}