Separate the interface definition and implementation in different packages. This allows the client to be completely unaware of the implementation.
Real world example
An Invoice generator may be created with ability to use different Tax calculators that may be added in the invoice depending upon type of purchase, region etc.
In plain words
Separated interface pattern encourages to keep the implementations of an interface decoupled from the client and its definition, so the client is not dependent on the implementation.
A client code may abstract some specific functionality to an interface, and define the definition of the interface as an SPI (Service Programming Interface is an API intended and open to be implemented or extended by a third party). Another package may implement this interface definition with a concrete logic, which will be injected into the client code at runtime (with a third class, injecting the implementation in the client) or at compile time (using Plugin pattern with some configurable file).
Programmatic Example
Client
InvoiceGenerator
class accepts the cost of the product and calculates the total
amount payable inclusive of tax.
1public class InvoiceGenerator {
2
3 private final TaxCalculator taxCalculator;
4
5 private final double amount;
6
7 public InvoiceGenerator(double amount, TaxCalculator taxCalculator) {
8 this.amount = amount;
9 this.taxCalculator = taxCalculator;
10 }
11
12 public double getAmountWithTax() {
13 return amount + taxCalculator.calculate(amount);
14 }
15
16}
The tax calculation logic is delegated to the TaxCalculator
interface.
1public interface TaxCalculator {
2
3 double calculate(double amount);
4
5}
Implementation package
In another package (which the client is completely unaware of) there exist multiple implementations
of the TaxCalculator
interface. ForeignTaxCalculator
is one of them which levies 60% tax
for international products.
1public class ForeignTaxCalculator implements TaxCalculator {
2
3 public static final double TAX_PERCENTAGE = 60;
4
5 @Override
6 public double calculate(double amount) {
7 return amount * TAX_PERCENTAGE / 100.0;
8 }
9
10}
Another is DomesticTaxCalculator
which levies 20% tax for international products.
1public class DomesticTaxCalculator implements TaxCalculator {
2
3 public static final double TAX_PERCENTAGE = 20;
4
5 @Override
6 public double calculate(double amount) {
7 return amount * TAX_PERCENTAGE / 100.0;
8 }
9
10}
These both implementations are instantiated and injected in the client class by the App.java
class.
1 var internationalProductInvoice = new InvoiceGenerator(PRODUCT_COST, new ForeignTaxCalculator());
2
3 LOGGER.info("Foreign Tax applied: {}", "" + internationalProductInvoice.getAmountWithTax());
4
5 var domesticProductInvoice = new InvoiceGenerator(PRODUCT_COST, new DomesticTaxCalculator());
6
7 LOGGER.info("Domestic Tax applied: {}", "" + domesticProductInvoice.getAmountWithTax());
Use the Separated interface pattern when