Simple Factory Pattern in Java
What is a Simple Factory Pattern
- Simple Factory pattern is a creational pattern which typically has a method that returns an instance of a class based on some conditionals.
- It’s not a GoF pattern and it’s different from the Factory pattern
- Since it’s a single method and it’s using conditionals, this is still harder to extend and often the better choice is to use the Factory pattern where the subclasses decide how they should be instantiated.
- Advantage - It hides the internal implementation
- Disadvantage - Harder to extend
Example
Below is a simple factory SimpleTaxCalculatorFactory, it has a single method getTaxCalculator
that returns an instance of tax calculator based on the value of it’s method parameters.
public class SimpleTaxCalculatorFactory {
public static TaxCalculationStrategy getTaxCalculator(ProductType product) throws Exception {
if(product == ProductType.GOLD) {
return new GoldTaxCalculator();
} else if(product == ProductType.PETROL) {
return new PetrolTaxCalculator();
} else {
throw new Exception("invalid type");
}
}
}
A TaxCalculator can use the factory to fetch the instance SimpleTaxCalculatorFactory.getTaxCalculator(productType, price)
.
public class TaxCalculator {
public double calculateTax(ProductType productType, double price) throws Exception {
return SimpleTaxCalculatorFactory.getTaxCalculator(productType).calculateTax(price);
}
}
If you would like to see the full example please check out Program Slicing in Java